输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:熟悉怎么根据前序和中序遍历确定一棵二叉树的方法后,怎么编码是关键。关于二叉树的大多数问题都是可以用递归的思路完成分别设置前序遍历的两个范围索引prestart,preend和中序遍历的两个索引midstart,midend。每次从中序遍历中寻找与pre[prestart]相等的mid[i],例如从前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}前序中的pre[prestart](1)和中序中的mid[3],以此划分为两部分。
剩下的递归调用就是边界的传值问题。
cur->left=_reConstructBinaryTree(pre,prestart+1,prestart+(i-midstart),mid,midstart,i-1);//前序的索引从前序中prestart的下一位到prestart+(i-midstart)这一位。下面同理,把数据带入很容易看懂。
cur->right=_reConstructBinaryTree(pre,prestart+(i-midstart)+1,preend,mid,i+1,midend);//右子树要跨过左子树,从左子树的右边索引加1为起始位置。
完整代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size()!=vin.size()||pre.size()==0)
return NULL;
TreeNode* root=_reConstructBinaryTree(pre,0,pre.size()-1,vin,0,vin.size()-1);
return root;
}
private:
//前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
TreeNode* _reConstructBinaryTree(vector<int> pre,int prestart,int preend,vector<int> mid,int midstart,int midend){
if(prestart>preend||midstart>midend)//判断没有左子树或者没有右子树
return NULL;
TreeNode* cur=new TreeNode(pre[prestart]);
for(int i=midstart;i<=midend;i++){
if(pre[prestart]==mid[i]){
cur->left=_reConstructBinaryTree(pre,prestart+1,prestart+(i-midstart),mid,midstart,i-1);
cur->right=_reConstructBinaryTree(pre,prestart+(i-midstart)+1,preend,mid,i+1,midend);
}
}
return cur;
}
};