zoukankan      html  css  js  c++  java
  • 【剑指offer】7.重建二叉树

    7.重建二叉树

    输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

    例如,给出

    前序遍历 preorder = [3,9,20,15,7]

    中序遍历 inorder = [9,3,15,20,7]

    返回如下的二叉树:

    3
    

    /

    9 20

    /  
    

    15 7

    th:前序遍历第一个数就是root节点,而我们用map记录中序顺序,用根节点区分左右节点 递归调用。

    time : O(n)

    space : O(n)

       static Map<Integer,Integer> result = new HashMap<>();
        public static TreeNode buildTree(int[] preorder, int[] inorder) {
            for(int i=0;i<inorder.length;i++){
                result.put(inorder[i],i);
            }
            return recur(preorder,0,preorder.length-1,0);
        }
    
        public static TreeNode recur(int [] pre,int preL,int preR,int inL){
            if(preL > preR){
                return null;
            }
            TreeNode root = new TreeNode(pre[preL]);
            int rootIndex = result.get(root.val);
            int size = rootIndex - inL;
            root.left = recur(pre,preL+1,preL+size,inL);
            root.right = recur(pre,preL+1+size,preR,inL+size+1);
            return root;
        }
    
  • 相关阅读:
    省选知识点
    寒假练习
    水题欢乐赛-套路
    2019年12月(2)
    洛谷P1347 排序
    Aizu
    2019年12月(1)
    【CSP2019】
    联系博主
    UVA1420 Priest John's Busiest Day【贪心】
  • 原文地址:https://www.cnblogs.com/qxlxi/p/12860681.html
Copyright © 2011-2022 走看看