题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:
对于前序遍历的区域R1,中序遍历区域R2,想办法将其分为左右区域,划分的方法为:
1、前序遍历先遍历根节点,所以R1的第0个元素rootValue为根节点
2、中序遍历先遍历左子树,后访问根节点,所以找到rootValue节点的相对位置index,该位置之前的节点都是左子树
3、现在可以确定:
根节点:R1[0]
左子树的先序遍历:R1[1,...index]
右子树的先序遍历:R1[index+1, .......]
左子树的中序遍历:R2[0, .....index-1]
右子树的中序遍历:R2[index+1,......]
class Solution {
public:
TreeNode* reConstructBinaryTreeCore(vector<int> &pre, int s1, int e1, vector<int> &vin, int s2, int e2)
{
if(s1>e1)
{
return NULL;
}
TreeNode *pNode = new TreeNode(pre[s1]);
//从vin中找到等于pre[s1]的位置index,肯定可以找到
int index = 0;
while(vin[s2+index] != pre[s1])
{
index++;
}
//根据切分点index继续切分左右子树
pNode->left = reConstructBinaryTreeCore(pre, s1+1, s1+index, vin, s2, s2+index-1);
pNode->right = reConstructBinaryTreeCore(pre, s1+index+1, e1, vin, s2+index+1, e2);
return pNode;
}
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
TreeNode *pNode = NULL;
pNode = reConstructBinaryTreeCore(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
return pNode;
}
};