【剑指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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章