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.
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
解析
递归构建左右子树即可。
代码
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty())
return NULL;
TreeNode* root = new TreeNode(preorder[0]);
vector<int> leftpre;
vector<int> rightpre;
vector<int> leftin;
vector<int> rightin;
int index;
for(int i=0;i<inorder.size();i++){
if(inorder[i] == preorder[0]){
index = i;
break;
}
}
for(int i=0;i<index;i++){
leftin.push_back(inorder[i]);
leftpre.push_back(preorder[i+1]);
}
for(int i=index+1;i<inorder.size();i++){
rightin.push_back(inorder[i]);
rightpre.push_back(preorder[i]);
}
root->left = buildTree(leftpre, leftin);
root->right = buildTree(rightpre, rightin);
return root;
}
};