2023-9-28 JZ7 重建二叉树

题目链接:重建二叉树

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param preOrder int整型一维数组
     * @param vinOrder int整型一维数组
     * @return TreeNode类
     */
    int [] pre = {0}, vin = {0};
    HashMap<Integer, Integer> map = new HashMap<>();
    public TreeNode reConstructBinaryTree (int[] preOrder, int[] vinOrder) {

        if (preOrder.length == 0 || vinOrder.length == 0) return null;
        this.pre = preOrder;
        this.vin = vinOrder;
        for (int i = 0; i < vin.length; i ++) map.put(vin[i], i);
        return dfs(0, pre.length - 1, 0, vin.length - 1);
    }

    public TreeNode dfs(int pl, int pr, int il, int ir) {
        if(pl > pr) return null;
        TreeNode root = new TreeNode(pre[pl]);
        int k = map.get(root.val);
        TreeNode left = dfs(pl + 1, pl + k - il, il, k - 1);
        TreeNode right = dfs(pl + k - il + 1, pr, k + 1, ir);
        root.left = left;
        root.right = right;
        return root;
    }
}

你可能感兴趣的:(深度优先,算法,剑指offer,树)