题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:做该题之前,需要明白二叉树的前序遍历、中序遍历和后序遍历的联系,前序遍历中,第一个数值是二叉树的根节点的值,在中序遍历中,二叉树的根节点位于序列的中间,左子树序列位于根节点的左边,右子树位于根节点的右边,因此我们需要扫面中序遍历序列找到根节点。这样根据根节点的值在前序遍历序列中找到左右子树的前序遍历序列,这样左右子树的前序和中序遍历序列就能得到。已经分别找到了左右子树的前序和中序遍历序列,可以用同样的方法构建左右子树,可以使用递归的方式来完成。
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre == null || in == null || pre.length == 0 || in.length == 0){
return null;
}
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);
}
return root;
}
}

本文详细介绍了如何通过给定的二叉树的前序和中序遍历序列来重建该二叉树的过程。利用前序遍历中根节点的位置和中序遍历中根节点的位置,可以将问题分解为构建左右子树的问题,进而使用递归方法解决。
243

被折叠的 条评论
为什么被折叠?



