


解题思路:
分治

class Solution {
    // 一个哈希表用于存储中序遍历中每个值对应的索引,用于快速查找
    HashMap<Integer,Integer> map = new HashMap<>();
    // 保存前序遍历的结果数组
    int[] preorder;
    // 主函数,传入前序和中序遍历的结果,返回重建的树的根节点
    public TreeNode deduceTree(int[] preorder, int[] inorder) {
        // 将前序遍历的结果存储在成员变量中,供递归函数使用
        this.preorder = preorder;
        // 将中序遍历的元素及其对应索引存入哈希表中
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        // 调用递归函数,参数是前序遍历的起始索引,中序遍历的起始和结束索引
        return recur(0, 0, inorder.length - 1);
    }
    // 递归函数用于构建树
    TreeNode recur(int pre_root, int in_left, int in_right) {
        // 如果中序遍历的起始索引大于结束索引,则返回null,表示子树为空
        if (in_left > in_right) return null;
        // 创建新的树节点作为根节点,它的值来自前序遍历的结果
        TreeNode root = new TreeNode(preorder[pre_root]);
        // 获取当前根节点在中序遍历中的索引
        int idx = map.get(preorder[pre_root]);
        // 构建左子树,下一个前序索引为当前的pre_root+1,中序范围为in_left到idx-1
        root.left = recur(pre_root + 1, in_left, idx - 1);
        // 构建右子树,下一个前序索引为pre_root加上左子树的大小(idx-in_left)+1,中序范围为idx+1到in_right
        root.right = recur(pre_root + (idx - in_left) + 1, idx + 1, in_right);
        // 返回构建好的树的根节点
        return root;
    }
}


















