Construct Binary Tree from Preorder & Inorder – Solution & Complexity

Solution Walkthrough

1. Recognize the Pattern

The key pattern is: the first element of any preorder slice is always that subtree's root, and looking up that value's position in the corresponding inorder slice splits the remaining nodes into the left and right subtrees.

2. Build the Algorithm

Advance one state transition at a time. Mark or update state before exploring dependent work.

3. Check Edge Cases

Test empty or minimal input, skewed shapes, duplicates where allowed, and impossible outcomes.

4. Solution and Complexity

Time: O(n) — a hash map lookup gives each value's inorder index in O(1), so every node is built exactly once. Space: O(n) for the value-to-index map plus O(h) recursion stack (O(n) worst case on a skewed tree).

All 5 languages below run and submit against the remote judge for this problem — Java/Go/Rust use the same real TreeNode structural-type support the judge added for the rest of the linked-list/tree track.

def build_tree(preorder: list[int], inorder: list[int]) -> TreeNode:
    index_of = {val: i for i, val in enumerate(inorder)}
    pre_iter = iter(preorder)

    def build(left: int, right: int):
        if left > right:
            return None
        val = next(pre_iter)
        node = TreeNode(val)
        mid = index_of[val]
        node.left = build(left, mid - 1)
        node.right = build(mid + 1, right)
        return node

    return build(0, len(inorder) - 1)

FAQ