题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路
这个构造过程是一个递归的过程。
1.先求出根节点(前序序列第一个元素)。
2.将根节点带入到中序遍历序列中求出左右子树的中序遍历序列。
3.通过左右子树的中序序列元素集合带入前序遍历序列可以求出左右子树的前序序列。
4.左右子树的前序序列第一个元素分别是根节点的左右儿子
5.求出了左右子树的4种序列可以递归上述步骤
疑问:
reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1)和
reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn)中的参数是怎么计算出来的?
解答:
startPre+1,指的是前序遍历左子树的开始位置,即前序遍历根节点的下一个节点。
i-startIn,i指的是中序遍历根节点的位置,减去中序遍历开始位置即左子树的长度。所以startPre+i-startIn是前序遍历左子树结束的位置。
i-startIn+startPre+1,即startPre+(i-startIn)+1,即从startPre位置越过左孩子及其子节点的偏移值再往下一个节点走。
以下为JAVA实现的代码:
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
if(startPre>endPre||startIn>endIn)
return null;
TreeNode root=new TreeNode(pre[startPre]);
for(int i=startIn;i<=endIn;i++)
if(in[i]==pre[startPre]){
root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
break;
}
return root;
}
}