← DSA
MEDIUM

Construct Binary Tree from Preorder and Inorder Traversal

PracticeNeetCode ↗LeetCode ↗

Given two integer arrays preorder and inorder representing the preorder and inorder traversal of a binary tree with unique values, reconstruct and return that binary tree.

Example

Input preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output [3,9,20,null,null,15,7]

Key Pointers

Step-by-Step Analysis

  1. Build a hashmap inorder_index mapping value → index in inorder.
  2. Keep a pointer pre_idx starting at 0 into preorder.
  3. Define build(left, right) over the current inorder segment; if left > right, return None.
  4. Take root_val = preorder[pre_idx], advance pre_idx, create a TreeNode(root_val).
  5. Look up mid = inorder_index[root_val]; recursively build the left subtree over inorder[left..mid-1] and the right subtree over inorder[mid+1..right], attach both, and return root.

Complexity

Time: O(n) — Space: O(n)

Code

def buildTree(preorder: list[int], inorder: list[int]) -> TreeNode | None:
    inorder_index = {val: i for i, val in enumerate(inorder)}
    pre_idx = 0

    def build(left: int, right: int) -> TreeNode | None:
        nonlocal pre_idx
        if left > right:
            return None
        root_val = preorder[pre_idx]
        pre_idx += 1
        root = TreeNode(root_val)
        mid = inorder_index[root_val]
        root.left = build(left, mid - 1)
        root.right = build(mid + 1, right)
        return root

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

Code Explanation

How the solution above works, piece by piece.

  1. inorder_index maps value → position in inorder, so finding the split point is O(1).
  2. pre_idx walks through preorder: each value taken is the root of the subtree currently being built.
  3. build(left, right) constructs the subtree whose values occupy inorder[left..right]; an empty range returns None.
  4. mid is the root's inorder position: build the left part left..mid−1 first, then the right part. The left subtree must be built first because preorder lists it first.
  5. O(n) time and O(n) space for the map.

Visual Walkthrough

Running it on preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]:

Using preorder for roots and inorder for the splitpreorder3920157inorder9315207left of 3right of 3preorder[0] = 3 is the root; its position in inordersplits the rest into left and right subtrees3920157
Preorder lists a root before its subtrees, so the next preorder value is always the root of the subtree being built. That value's position in inorder says which values go left (before it) and right (after it). Repeating this builds the tree on the right.
rootleft subtree

Video Explanation

NeetCode — Construct Binary Tree from Preorder and Inorder Traversal, LeetCode 105