【LeetCode】 105. Construct Binary Tree from Preorder and Inorder Traversal Construct a binary tree from preorder and inorder traversal sequence (JAVA)

【LeetCode】 105. Construct Binary Tree from Preorder and Inorder Traversal Construct a binary tree (Medium) (JAVA) from preorder and inorder traversal sequence

Subject address: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

Title description:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Topic

The binary tree is constructed according to the pre-order and middle-order traversal of a tree.

Note:
You can assume that there are no duplicate elements in the tree.

Problem solving method

1. The root node of the pre-order traversal is in the first one; the root node of the middle-order traversal is in the middle. If the root node is found, it can be divided into left and right subtrees.
2. Iteratively update the complete tree

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return bH(preorder, inorder, map, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode bH(int[] preorder, int[] inorder, Map<Integer, Integer> map, int pStart, int pEnd, int iStart, int iEnd) {
        if (pStart > pEnd || iStart > iEnd) return null;
        int mid = map.get(preorder[pStart]);
        TreeNode root = new TreeNode(preorder[pStart]);
        root.left = bH(preorder, inorder, map, pStart + 1, pStart + mid - iStart, iStart, mid - 1);
        root.right = bH(preorder, inorder, map, pStart + mid - iStart + 1, pEnd, mid + 1, iEnd);
        return root;
    }
}

Execution time: 3 ms, defeated 81.03% of users
in all Java submissions Memory consumption: 40.1 MB, defeated 66.67% of users in all Java submissions

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/105800792