# 105. Construct Binary Tree from Preorder and Inorder 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 buildTree(int[] preorder, int[] inorder) {
        Map<Integer, Integer> inMap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            inMap.put(inorder[i], i);
        }
        return dfs(preorder, inorder, inMap, 0, preorder.length-1, 0, inorder.length-1);
    }
    private TreeNode dfs(int[] preorder, int[] inorder, Map<Integer, Integer> inMap, int preStart, int preEnd, int inStart, int inEnd) {
        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 inRootIdx = inMap.get(rootVal);
        int leftSize = inRootIdx - inStart; // use inOrder to get leftPartSize
        TreeNode root = new TreeNode(rootVal);
        root.left = dfs(preorder, inorder, inMap, preStart+1, preStart+leftSize, inStart, inRootIdx-1);
        root.right = dfs(preorder, inorder, inMap, preStart+leftSize+1, preEnd, inRootIdx+1, inEnd);
        return root;
    }
}
/***

            x L                      L x R
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]


how can we determine left tree range? use inorder and preorder to find it

->        int leftSize = inRootIdx - inStart; // use inOrder to get leftPartSize
**/
```
