剑指offer面试题7(java版):重建二叉树

welcome to my blog

剑指offer面试题7(java版):重建二叉树

题目描述

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

第四次做; 理清递归函数逻辑, 带数组的话, 先写数组的操作范围
/*
根据前序遍历可以找到根节点, 有了根节点之后可以在中序遍历中定位到根节点, 从而找出属于左子树和右子树的值
使用递归重建二叉树
*/
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        //input check
        if(pre==null || pre.length==0)
            return null;
        //
        TreeNode root = core(pre, in, 0, pre.length-1, 0, in.length-1);
        return root;
    }
    //递归函数逻辑:操作范围[preL,preR], [inL, inR], 现在pre中找到根节点的val, 创建根节点(当前条件), 
    //找出左子树的操作范围, 构建左子树(新条件新递归), 根节点连接左子树的根节点
    //找出右子树的操作范围, 构建右子树(新条件新递归), 根节点连接右子树的根节点
    //返回当前的根节点(当前条件)
    private TreeNode core(int[] pre, int[] in, int preL, int preR, int inL, int inR){
        //base case
        if(preL>preR)
            return null;
        //
        //创建根节点
        TreeNode root = new TreeNode(pre[preL]);
        //确定左右子树的范围
        //记录左子树节点的个数
        int leftCount = 0;
        for(int i=inL; i<=inR; i++){
            if(in[i] == pre[preL])
                break;
            leftCount++;
        }
        //创建左子树(新条件新递归), 根节点连接左子树的根节点
        root.left = core(pre, in, preL+1, preL+leftCount, inL, inL+leftCount-1);
        //创建右子树(新条件新递归), 根节点连接右子树的根节点
        root.right = core(pre, in, preL+leftCount+1, preR, inL+leftCount+1, inR);
        //返回当前的根节点
        return root;
    }
}
第三次做, 递归逻辑:在pre,in的指定范围中找到根节点及左右子树的范围,根节点分别连接已经连接好的左右子树(如果左右子树存在的话); 如果提前判断了左右子树是否存在的话, 就不用写base case了; 像这种用到左右子树的题, 尽量先判断左右子树是否存在
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre==null || in == null || pre.length!=in.length)
            return null;
        return Core(pre, in, 0, pre.length-1, 0, in.length-1);
    }
    public TreeNode Core(int[] pre, int[] in, int preLeft, int preRight, int inLeft, int inRight){
        //base case
        //if(preLeft==preRight)
            //return new TreeNode(pre[preLeft]);
        //
        //先找到根
        TreeNode root = new TreeNode(pre[preLeft]);
        int rootVal = pre[preLeft];
        //在in中找到左右子树的分界
        int index = inLeft;
        while(in[index] != rootVal)
            index++;
        //左右子树长度
        int leftLen = index - inLeft;
        int rightLen = inRight - index;
        //左子树存在的话,根节点连接已经连好的左子树
        if(leftLen>0)
            root.left = Core(pre, in, preLeft+1, preLeft+leftLen, inLeft, index-1);
        //右子树存在的话,根节点连接已经连好的右子树
        if(rightLen>0)
            root.right = Core(pre, in, preLeft+leftLen+1, preRight, index+1, inRight);
        return root;
    }
}
第二次做
  • 主要的心得就是:使用左右子树或者左右孩子之前,先判断有没有左右子树,有没有左右孩子。 这是一个习惯思维
  • 本题中,由于提前判断了是否有左右子树,所以就没有base case了
  • 我觉得第二遍做的时候,那个心得是可以的: 传入的实参要确保有效,不要通过下一轮递归的base case判断是否有效。 本来能在当地解决的问题,就没有必要放到别的地方处理了
  • 想法可能会不断改变
//细节:其实坐标不是0!!! 这是处理部分数组的共有细节
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre==null||pre.length==0)return null;
        return Core(pre, in, 0, pre.length-1, 0, in.length-1);
    }
    public TreeNode Core(int[] pre, int[] in, int preLeft, int preRight, int inLeft, int inRight){
        //base case
        //
        TreeNode root = new TreeNode(pre[preLeft]);
        //如果有左子树的话, 如果有右子树的话
        //如何判断是否有左右子树? 本题可以通过长度判断
        int rootIndexInIn = inLeft;
        while(in[rootIndexInIn] != pre[preLeft])
            rootIndexInIn++;
        int leftSubTreeLen = rootIndexInIn - inLeft;
        int rightSubTreeLen = inRight - rootIndexInIn;
        if(leftSubTreeLen>0)
            root.left = Core(pre, in, preLeft+1, preLeft+leftSubTreeLen, inLeft, rootIndexInIn-1);
        if(rightSubTreeLen>0)
            root.right = Core(pre, in, preLeft+leftSubTreeLen+1, preRight, rootIndexInIn+1, inRight);
        return root;
第二次做, 仍用了很久, 倒是思路比第一遍清晰
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        //input check
        if(pre==null || in==null) return null;
        //
        int N = pre.length;
        TreeNode root = Core(pre, in, 0, N-1, 0, N-1);
        return root;
    }
    //找出当前给定范围下的根节点, 将根节点与其左右子树的根节点(如果有的话)相连, 最后返回根节点
    //关键在于在给定的范围中找出左右子树
    //传递实参时要保证实参不越界! 不要把对实参的检查放到base case中 
    //在数组的一部分上进行操作, 由其要注意边界! 左边界都会有preLeft, inLeft; 右边界都会有preRight, inRight
    public TreeNode Core(int[] pre, int[] in, int preLeft, int preRight, int inLeft, int inRight){
        //base case
        //if (preLeft == preRight) return new TreeNode(pre[preLeft]);
        //
        TreeNode node = new TreeNode(pre[preLeft]);
        int temp = 0;
        while (in[inLeft + temp] != pre[preLeft])
            temp++;
        if(temp>0)
            node.left = Core(pre, in, preLeft + 1, preLeft + temp, inLeft, inLeft + temp - 1);
        if(inRight - inLeft - temp > 0)
            node.right = Core(pre, in, preLeft + temp + 1, preRight, inLeft + temp + 1, inRight);
        return node;
    }
}

思路

  • 画图思考不容易越界
  • 体会递归思想
  • 本题在递归中传递的参数中, 不变的是两个表示前序遍历和中序遍历的数组, 变化的是代表子树起始索引和终止索引的值

复杂度

时间复杂度: 不断的二分, 所以时间复杂度是O(logn)
空间复杂度: 没有使用额外的内存空间, 所以空间复杂度是O(1)

/**
 * 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) {
        // 1.健壮性判断
        if(pre.length != in.length || pre.length <=0 || in.length <=0 )
            return null;
        // 2.开始正常执行
        TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);
        return root;
    }
    public TreeNode reConstructBinaryTree(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd){
        /*
        1. 在前序遍历中找到根节点
        2. 在中序遍历中找到根节点
        3. 找出左子树(注意判断左子树是否存在)及其对应的前序遍历和中序遍历结果
        4. 找出右子树(注意判断右子树是否存在)及其对应的前序遍历和中序遍历结果
        */
        //1.
        TreeNode root = new TreeNode(pre[preStart]);
        //2.
        int leftLen=0;
        for(int i=inStart; i<= inEnd; i++){
            if(in[i] == pre[preStart])
                break;
            leftLen++;
        }
        //3.
        if(leftLen>0){
            int preStartLeft = preStart+1;
            int preEndLeft = preStart+leftLen;
            int inStartLeft = inStart;
            int inEndLeft = inStart + leftLen -1;
            root.left = reConstructBinaryTree(pre, preStartLeft, preEndLeft, in, inStartLeft, inEndLeft);
        }
        if((preEnd - preStart) - leftLen > 0 ){
            int preStartRight = preStart+leftLen+1;
            int preEndRight = preEnd;
            int inStartRight = inStart+leftLen+1;
            int inEndRight = inEnd;
            root.right = reConstructBinaryTree(pre, preStartRight, preEndRight, in, inStartRight, inEndRight);
        }
        return root;
    }
}
最优解
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;
    }
    //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
    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;
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值