[LC] 106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        Map<Integer, Integer> mymap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            mymap.put(inorder[i], i);
        }
        return helper(0, inorder.length - 1, 0, postorder.length - 1, postorder, mymap);
    }
    
        private TreeNode helper(int inLeft, int inRight, int postLeft, int postRight, int[] postorder, Map<Integer, Integer> mymap) {
        if (inLeft > inRight) {
            return null;
        }
        TreeNode cur = new TreeNode(postorder[postRight]);
        int index = mymap.get(postorder[postRight]);
        int leftSize = index - inLeft;
        // postRight for left just add up leftSize
        cur.left = helper(inLeft, index - 1, postLeft, postLeft + leftSize - 1, postorder, mymap);
        cur.right = helper(index + 1, inRight, postLeft + leftSize, postRight - 1, postorder, mymap);
        return cur;
    }
}
posted @ 2020-01-09 13:16  xuan_abc  阅读(114)  评论(0编辑  收藏  举报