LeetCode Notes_#104_从中序与后序遍历序列构造二叉树

LeetCode Notes_#104_从中序与后序遍历序列构造二叉树

Contents

题目

根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出

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

返回如下的二叉树:

    3
   / 
  9  20
    /  
   15   7

思路分析

这一题的思路与剑指Offer_#7_重建二叉树非常类似,是一个变式,如果掌握了分析题目的方法,那么这一题也很容易。
唯一的区别在于递归调用的参数不一样。参考如下图解。

解答

class Solution {
    HashMap<Integer,Integer> map = new HashMap<>();
    int[] post;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder == null || postorder == null) return null;
        int inLen = inorder.length;
        int postLen = postorder.length;
        if(inLen == 0 || postLen == 0 || inLen != postLen) return null;
        post = postorder;
        for(int i = 0;i <= inLen - 1;i++){
            map.put(inorder[i],i);
        }
        return recur(0,postLen - 1,0,inLen - 1);
    }

    private TreeNode recur(int postL,int postR,int inL,int inR){
        if(postL > postR || inL > inR) return null;
        //根节点的值是后序遍历序列的最后一个值
        int rootValue = post[postR];
        TreeNode root = new TreeNode(rootValue);
        int rootIdx = map.get(rootValue);
        root.left = recur(postL,postR - inR + rootIdx - 1,inL,rootIdx - 1);
        root.right = recur(postR - inR + rootIdx,postR - 1,rootIdx + 1,inR);
        return root;
    }
}

复杂度分析

时间复杂度:O(n),需要使用主定理分析
空间复杂度:O(n),map存储了所有节点,最差情况下,递归调用n层,占用栈空间O(n)

原文地址:https://www.cnblogs.com/Howfars/p/13441922.html