# 889. Construct Binary Tree from Preorder and Postorder Traversal



```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {

        Map<Integer, Integer> postMap = new HashMap<>();
        for (int i = 0; i < postorder.length; i++) {
            postMap.put(postorder[i], i);
        }
        return dfs(preorder, postorder, postMap, 0, preorder.length-1, 0, postorder.length-1);
    }
    private TreeNode dfs(int[] preorder, int[] postorder, Map<Integer, Integer> postMap, int preStart, int preEnd, int postStart, int postEnd) {
        if (preStart > preEnd) {
            return null;
        }
        if (preStart == preEnd) { // means it's the only element, the last one, because we use preStart to make TreeNode
            return new TreeNode(preorder[preStart]);
        }

        int rootVal = preorder[preStart];
        int secondPostRootIdx = postMap.get(preorder[preStart+1]);
        int leftSize = secondPostRootIdx - postStart + 1; // use postOrder to get leftPartSize
        TreeNode root = new TreeNode(rootVal);
        root.left = dfs(preorder, postorder, postMap, preStart+1, preStart+leftSize, postStart, secondPostRootIdx);
        root.right = dfs(preorder, postorder, postMap, preStart+leftSize+1, preEnd, secondPostRootIdx+1, postEnd-1);
        return root;
    }

}
/**
            x x
preorder = [1,2,4,5,3,6,7], 
                         x
postorder = [4,5,2,6,7,3,1]

 */
```
