重构二叉树

xiaoxiao2021-02-27  469

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。


解答

先说思路,模拟手算的步骤。

在文中默认前序是pre[],中序in[]

重构二叉树第一件事就是找到root,也就是说,找到pre[0],然后构建一个节点,作为根节点。 然后再去中序里面找,找到之后,左边的就一定是根节点左边的,同理,右边一定是属于右节点的。 拿例子举例:

后面的步骤也是这样。 对左子树再做相同的事。 右边也一样。

/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { return re(pre,0,pre.length-1,in,0,in.length-1); } public TreeNode re(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=re(pre,startPre+1,i-startIn+startPre,in,startIn,i-1); root.right=re(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); break; } } return root; } }

还是单独详解一下:

下面的1~8均指图上的标号

首先,1到2之间的是左子树的前序,5到6是左子树的中序; 3到4是右子树的的前序,7到8是右子树的中序。

所以,写代码时就可以用递归了。 代码中i是指在中序中找到的root的位置,i-startIn也就是左子树的节点个数,在前序中(i-startIn)+startPre+1也就找到了右子树前序开始的位置(即图中位置3,其中+1是root节点占了一个)。 要点:i-startIn是左子树的节点个数,把它看成一个整体。

转载请注明原文地址: https://www.6miu.com/read-566.html

最新回复(0)