输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:
1、前序遍历第一个元素1即为根节点;
2、在中序遍历中找到1,1左边的元素属于根节点的左子树,右边的元素属于右子树;
3、因此可以得到根节点的左子树的前序遍历和中序遍历序列,同理可以得到右子树的前序遍历和中序遍历序列;
4、很明显是一个递归的过程
/**
* 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.empty()||vin.empty()||pre.size()!=vin.size())
return NULL;
return helper(pre,0,pre.size()-1,vin,0,vin.size()-1);
}
TreeNode* helper(vector<int>& pre,int pre_L,int pre_R,vector<int>& vin,int vin_L,int vin_R){
int rootVal=pre[pre_L];
TreeNode* root=new TreeNode(rootVal);
root->left=NULL;
root->right=NULL;
if(pre_L==pre_R){
if(vin_L==vin_R&&pre[pre_L]==vin[vin_L])
return root;
}
int rootPos=vin_L;
while(rootPos<=vin_R&&vin[rootPos]!=rootVal)
rootPos++;
int len=rootPos-vin_L;
if(len>0)
root->left=helper(pre,pre_L+1,pre_L+len,vin,vin_L,rootPos-1);
if(rootPos<vin_R)
root->right=helper(pre,pre_L+len+1,pre_R,vin,rootPos+1,vin_R);
return root;
}
};