Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int pre_id=0;
int inorder_begin=0;
int inorder_end=inorder.size()-1;
return build_tree(pre_id,inorder_begin,inorder_end,preorder,inorder);
}
TreeNode *build_tree(int &preid, int in_begin, int in_end, vector<int> &preorder,vector<int> &inorder)
{
if(in_begin>in_end || preid >= preorder.size())
return NULL;
TreeNode *root=new TreeNode(preorder.at(preid));
if(in_begin==in_end)
{
preid++;
return root;
}
int i=0;
for(;i<inorder.size();i++)
{
if(inorder.at(i)==root->val)
break;
}
preid++;
TreeNode* leftchild=build_tree(preid,in_begin,i-1,preorder,inorder);
TreeNode* rightchild=build_tree(preid,i+1,in_end,preorder,inorder);
root->left=leftchild;
root->right=rightchild;
return root;
}
};