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.

分析:通过一个二叉树的先序遍历和中序遍历可以确定一个二叉树。先序遍历的第一个元素对应二叉树的根结点,由于在中序遍历中左子树和右子树的中序遍历序列分别在根节点两侧,因此我们可以确定左子树和右子树的中序遍历序列。在先序遍历序列中,根节点后面是左子树的先序遍历序列,左子树的先序遍历序列后是右子树的先序遍历序列。由于同一个树的线序遍历序列和中序遍历序列具有相同的长度,因此我们可以根据中序序列中左子树中序序列的长度确定先序遍历序列中左子树的先序遍历序列。进而先序遍历序列中右子树的先序遍历序列也可以确定。之后,我们可以递归的求解。代码如下:

 1 class Solution {
 2 public:
 3     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
 4         return build_Tree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
 5     }
 6     
 7     TreeNode *build_Tree(vector<int>::iterator pre_b, vector<int>::iterator pre_e, vector<int>::iterator in_b, vector<int>::iterator in_e){
 8         if(pre_b == pre_e || in_b == in_e) return NULL;
 9         
10         TreeNode *root = new TreeNode(*pre_b);
11         auto root_p = find(in_b, in_e, *pre_b);
12         auto tmp = next(pre_b, distance(in_b, root_p)+1);
13         
14         root->left = build_Tree(next(pre_b), tmp, in_b, root_p);
15         root->right = build_Tree(tmp, pre_e, next(root_p), in_e);
16         
17         return root;
18     }
19 };

 

posted on 2014-08-16 23:28  Ryan-Xing  阅读(159)  评论(0编辑  收藏  举报