Construct Binary Tree from Preorder and Inorder Traversal
Problem
You are given two integer arrays that describe the same binary tree: preorder, the sequence of values visited by a preorder traversal (node, then left subtree, then right subtree), and inorder, the sequence visited by an inorder traversal (left subtree, node, right subtree). All values are distinct. Rebuild the tree and return its root.
- Both arrays have the same length, between 1 and 8,000.
- Values are distinct integers (negative values allowed).
- The two arrays contain the same set of values and describe one valid tree.
Examples
preorder = [6, 2, 1, 4, 9, 12],inorder = [1, 2, 4, 6, 9, 12]→[6, 2, 9, 1, 4, None, 12]. The root is 6; ininorderthe[1, 2, 4]to its left is the whole left subtree and[9, 12]is the right subtree.preorder = [5],inorder = [5]→[5].preorder = [4, 7, 10],inorder = [10, 7, 4]→[4, 7, None, 10]. A left-leaning chain: each root is the last element of its inorder slice.
Hints
- What does the first element of
preordertell you? Where does that value appear ininorder, and what does its position split? - Once you know the left subtree has
Lnodes, which slice ofpreorderdescribes it? - Recurse on index ranges rather than copying subarrays, and precompute a value-to-index map for
inorderso each split is O(1).
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.