Offer07.重建二叉树/Solution.java
/**
 * Definition for a binary tree node.
 */
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    int[] preorder;
    HashMap<Integer, Integer> dict = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        for (int i = 0; i < inorder.length; i++) {
            dict.put(inorder[i], i);
        }

        return recur(0, 0, inorder.length - 1);
    }

    TreeNode recur(int root, int left, int right) {
        if (left > right) {
            return null;
        }
        TreeNode head = new TreeNode(preorder[root]);

        int i = dict.get(preorder[root]);
        head.left = recur(root + 1, left, i - 1);
        head.right = recur(root + i - left + 1, i + 1, right);
        return head;
    }
}