106. Construct Binary Tree from Inorder and Postorder Traversal

一、题目

  1、审题

  2、分析

    给出一个不含有重复节点值的二叉树的中序、后序遍历序列,求原二叉树的序列。

二、解答

  1、思路:

    方法一、

      采用递归的方式还原二叉树。

      ①、后序遍历的末尾节点为 root 节点,root 节点值在 中序遍历中的节点下标为 inIndex;

      ②、则中序遍历的 (0, inIndex - 1) 为 root的左子树, (inIndex + 1, len)为 root 的右子树。

      ③、root 左、右子树的后序遍历又与原后序遍历序列中相对应。

public TreeNode buildTree3(int[] inorder, int[] postorder) {
    
        if(inorder.length == 1)
            return null;
        
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) 
            map.put(inorder[i], i);
        
        return helperBuildTree(0, inorder.length - 1, inorder, postorder.length-1, postorder, map);
    }
    
    
    private TreeNode helperBuildTree(int inStart, int inEnd, int[] inorder, 
                            int postEnd, int[] postorder, Map<Integer, Integer> map) {
        
        if(inStart > inEnd || postEnd < 0)    // 跳出递归条件
            return null;
        
        TreeNode root = new TreeNode(postorder[postEnd]);
        int inIndex = map.get(root.val);            // postEnd - (inEnd - index  + 1)
//        root.left = helperBuildTree(inStart, inIndex - 1, inorder, inIndex - 1, postorder, map);    -- Wrong
        // postEnd - (inEnd - inIndex  + 1) :  左子树的头结点在后续遍历的下标
        root.left = helperBuildTree(inStart, inIndex - 1, inorder, postEnd - (inEnd - inIndex  + 1), postorder, map);
        root.right = helperBuildTree(inIndex + 1, inEnd, inorder, postEnd - 1, postorder, map);
        
        return root;
    }
原文地址:https://www.cnblogs.com/skillking/p/9734203.html