首页 > 其他 > 详细

Leetcode | Construct Binary Tree from Inorder and (Preorder or Postorder) Traversal

时间:2014-05-19 18:44:01      阅读:348      评论:0      收藏:0      [点我收藏+]

Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

递归构建。

思路就是: preorder可以定位到根结点,inorder可以定位左右子树的取值范围。

1. 由preorder得到根结点;把preorder第一个点删掉;

2. 先建左子树;再建右子树;

通过一个区间来表示左右子树的取值范围。因为inorder左右子树的范围都是连续的。中间就是root。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
 4         return recursive(preorder, inorder, 0, inorder.size() - 1);
 5     }
 6     
 7     TreeNode* recursive(vector<int> &preorder, vector<int> &inorder, int s, int e) {
 8         if (s > e) return NULL;
 9         if (preorder.empty()) return NULL;
10         TreeNode *root = new TreeNode(preorder.front());
11         preorder.erase(preorder.begin());
12         
13         int i = s;
14         for (; i <= e && inorder[i] != root->val; ++i);
15         root->left = recursive(preorder, inorder, s, i - 1);
16         root->right = recursive(preorder, inorder, i + 1, e);
17     }
18 };
bubuko.com,布布扣

Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

和上面类似。有两点不同。

1. postorder,最后一个元素是根结点。

2. 先构建右子树,再构建左子树。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
 4         return recursive(postorder, inorder, 0, inorder.size() - 1);
 5     }
 6     
 7     TreeNode* recursive(vector<int> &postorder, vector<int> &inorder, int s, int e) {
 8         if (s > e) return NULL;
 9         if (postorder.empty()) return NULL;
10         TreeNode *root = new TreeNode(postorder.back());
11         postorder.pop_back();
12         
13         int i = s;
14         for (; i <= e && inorder[i] != root->val; ++i);
15         root->right = recursive(postorder, inorder, i + 1, e);
16         root->left = recursive(postorder, inorder, s, i - 1);
17     }
18 };
bubuko.com,布布扣

 

Leetcode | Construct Binary Tree from Inorder and (Preorder or Postorder) Traversal,布布扣,bubuko.com

Leetcode | Construct Binary Tree from Inorder and (Preorder or Postorder) Traversal

原文:http://www.cnblogs.com/linyx/p/3734763.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!