106. 从中序与后序遍历序列构造二叉树

小豆丁 1年前 ⋅ 1192 阅读
106. 从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

解析

一样的题目,找到关联点,后序遍历的最后一个节点就是根节点。

class Solution {
    Map<Integer,Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        //中序遍历的最后一个节点就是根节点,然后在前序遍历中找到根节点的位置就可以确定左右子树的长度
        
        for(int i = 0 ;i < inorder.length;i++){
            map.put(inorder[i],i);
        }
        return helper(inorder,postorder,0,inorder.length - 1,0,postorder.length - 1);
    }
    public TreeNode helper(int[] inorder, int[] postorder,int in1,int in2,int post1,int post2){
        if(in1>in2){
            return null;
        }
        TreeNode root = new TreeNode(postorder[post2]);
        int inRootIndex = map.get(postorder[post2]);
        int leftLen = inRootIndex - 1 - in1 + 1;
        int rightLen = in2 - (inRootIndex+1)+1;
        root.left = helper(inorder,postorder,in1,inRootIndex-1,post1,post1+leftLen-1);
        root.right = helper(inorder,postorder,inRootIndex+1,in2,post1+leftLen,post2 - 1);

        return root;
    }
}