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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/littlehaes/article/details/91383163

welcome to my blog

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

题目描述

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

思路

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

复杂度

时间复杂度: 不断的二分, 所以时间复杂度是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;
    }
}

猜你喜欢

转载自blog.csdn.net/littlehaes/article/details/91383163