输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/**
* 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 construct(pre,0,pre.size()-1,vin,0,vin.size()-1);
}
TreeNode* construct(vector<int>pre,int ps,int pe,vector<int>vin,int is,int ie)
{
if(ps>pe || is>ie)
return NULL;
// 前序遍历的第一结点为根节点
int value=pre[ps];
int index=is;
//for(int i=)
while(is<=ie){
if(value==vin[index])
break;
index++;
}
// 创建根节点,赋值
TreeNode* node=new TreeNode(value);
// 递归调用构建当前节点的左子树
node->left=construct(pre,ps+1,ps+index-is,vin,is,index-1);
// 递归调用构建当前节点的右子树
node->right=construct(pre,ps+index-is+1,pe,vin,index+1,ie);
return node;
}
};