title
link Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
solution
class Solution {
public:
TreeNode* f(vector<int>& pre,vector<int> mid,int a,int b,int c,int d){
if(a>b||c>d)
return NULL;
int v=pre[a];
int m=c;
for(int i=c;i<=d;i++){
if(mid[i]==v){
m=i;
break;
}
}
TreeNode *root=new TreeNode(pre[a]);
root->left=f(pre,mid,a+1,a+m-c,c,m-1);
root->right=f(pre,mid,a+m-c+1,b,m+1,d);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode* root=f(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
return root;
}
};