题目
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
分析
《剑指Offer》上的重建二叉树原题,根据前序序列是根节点,中序序列当前根节点左侧全是左子树,右侧全是右子树的特点重建,需要注意的是,要计算出左子树长度,并在前序序列中截取出左子树和右子树的部分。
class Solution {
public:
TreeNode* build(vector& preorder, int pre_beg, int pre_end, vector& inorder, int in_beg, int in_end){
if(pre_beg>=pre_end||in_beg>=in_end){
return NULL;
}
int i;
for(i=in_beg;i0){//如果左子树存在,则在前序序列当前位置的后leftLen个属于左子树
root->left=build(preorder,pre_beg+1,pre_beg+leftLen+1,inorder,in_beg,i);
}
if(leftLenright=build(preorder,pre_beg+leftLen+1,pre_end,inorder,i+1,in_end);//前序和中序区间按照[beg,end)截取
}
return root;
}
TreeNode* buildTree(vector& preorder, vector& inorder) {
if(preorder.size()!=inorder.size()||preorder.empty()||inorder.empty())
return NULL;
return build(preorder,0,preorder.size(),inorder,0,inorder.size());
}
};