剑指offer_重建二叉树java版
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回
前序遍历{1,2,4,7,3,5 ,6,8}
中序遍历{4,7,2,1,5,3,8,6}
思路:前序遍历中第一个节点一定是根节点,然后是左子树和右子树的节点,然后在中序遍历中找到这个根节点,根节点左侧的就是左子树,右侧的就是右子树.例如本例中:1是根节点,在中序遍历中在第4位置上,所以,1是根节点,[2,4,7]是左子树的,[3,5,6,8]是右子树的然后就可以递归建树,因为子树也是树,都符合这个操作。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static TreeNode build(int [] pre,int [] in,int start ,int end,int y1,int y2) {
if(start>=end)return null;
if(start>=pre.length)return null;
int len=pre.length;
TreeNode root=new TreeNode(pre[start]);
int cnt=0;
for(int i=y1;i<y2;i++)
{
if(pre[start]!=in[i]){cnt++;}
else break;
}
//这是在找根节点在中序遍历中的位置
// System.out.println(cnt);
if(start+1<len)
root.left=build(pre,in,start+1,start+cnt+1,y1,y1+cnt);
if(start+cnt+1<len)
root.right=build(pre,in,start+cnt+1,end,y1+cnt+1,y2);
return root;
}
public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return build(pre,in,0,pre.length,0,pre.length);
}
}
解释一下start,end对应的是前序遍历建树的范围,y1,y2是中序遍历中建树的范围.例如例子中,得到根节点左子树时,前序中建树范围是[2,4,7]而中序建树范围是[4,7,2];建立右子树时,前序范围是[3,5,6,8]而中序是[5,3,8,6],这些参数就是用来固定范围的,因为我们就使用了2个数组。当然更好理解的方法是下面这一种,从大佬的代码中学来的,就是直接生成新的数组,比如生成新的数组[2,4,7],[4,7,2],[3,5,6,8],[5,3,8,6]等,这样就更加容易理解,不用去考虑这么多的界限范围问题了。代码如下:
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0||in.length == 0){
return null;
}
TreeNode node = new TreeNode(pre[0]);
for(int i = 0; i < in.length; i++){
if(pre[0] == in[i]){
node.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i));
node.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in, i+1,in.length));
}
}
return node;
}
}