The problem of reorganizing the binary tree in the front and middle order?

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) {
            return null;
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; iPP) {
            map.put(inorder[i], i);
        }

        return preIn(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
    }

    private TreeNode preIn(int[] preorder, int pl, int pr, int[] inorder, int il, int ir, HashMap<Integer, Integer> map) {
        if (pl > pr) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[pl]);
        Integer topIndex = map.get(preorder[pl]);

        root.left = preIn(preorder, pl + 1, pl + topIndex - il, inorder, il, topIndex - 1, map);
        root.right = preIn(preorder, pl + topIndex + 1 - il, pr, inorder, topIndex + 1, ir, map);
        return root;
    }

Why does the preorder range in recursion have a-il (pl+topIndex-il) left subtree that should not be pl+1,pl+topIndex, right subtree pl+topIndex,pr?

Mar.14,2021
  • Algorithm: similar to N SUM problem solving

    topic description similar to the problem of N SUM, the idea comes from a small task encountered in the work, abstracted out: has m items, and gives the unit price of each item, P1 br P2, P3 br. Now there are n orders, and the total amount of each ord...

    Mar.28,2022
Menu