题目描述:
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) {
if(inorder.empty()||preorder.empty()) return NULL;
else
{
int root_val=preorder[0];
int index=0;
for(int i=0;i<inorder.size();i++)
{
if(inorder[i]==root_val)
{
index=i;
break;
}
}
TreeNode* root=new TreeNode(root_val);
vector<int> v1(preorder.begin()+1,preorder.begin()+1+index);
vector<int> v2(inorder.begin(),inorder.begin()+index);
root->left=buildTree(v1,v2);
vector<int> v3(preorder.begin()+1+index,preorder.end());
vector<int> v4(inorder.begin()+1+index,inorder.end());
root->right=buildTree(v3,v4);
return root;
}
}
};