Rebuild a Binary Tree from Pre- and In-Order Sequences
Trees & GraphsModel answerLast updated
Given preorder and inorder traversal arrays of a binary tree with unique values, reconstruct the tree in O(n) time and O(n) space.
Rebuild a Binary Tree from Pre- and In-Order Sequences
You are given two integer arrays, preorder and inorder, produced by traversing the same binary tree. All node values in the tree are unique.
preorder[i]is the value of the i-th node visited in a preorder (root → left → right) walk.inorder[i]is the value of the i-th node visited in an inorder (left → root → right) walk.
Reconstruct the tree and return its root node.
Requirements
- Your solution must run in O(n) time and use O(n) extra space (not counting the output tree itself). Explain why a naïve implementation falls short of O(n) and what you do to meet the target.
- Describe how you would validate the inputs. List the checks you would add, explain why each one is necessary, and state what your function should do when an input cannot correspond to any valid binary tree.
- Write unit tests covering at minimum: an empty tree, a single node, a left-skewed tree, a right-skewed tree, a balanced tree, and at least two invalid-input cases.
Function signature (Python)
def build_tree(preorder: list, inorder: list) -> TreeNode | None:
...
where TreeNode has the attributes val, left, and right.
Examples
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
Reconstructed tree:
3
/ \
9 20
/ \
15 7
preorder = [1]
inorder = [1]
→ A single root node with no children.
preorder = [1, 2]
inorder = [1, 2] ← 2 is to the right of 1 in inorder
→ Root 1 with right child 2.
Constraints
0 ≤ n ≤ 10^5- All values are unique and hashable.
- Both arrays contain the same set of values (if valid).
Hints
Hint 1
The first element of preorder is always the root of the current subtree. Once you know the root, its position in inorder tells you exactly how many nodes belong to its left subtree versus its right subtree.
Hint 2
A linear scan to find the root's position in inorder at every level gives O(n²) on skewed trees. Store a hash map from value to inorder index before you start, so each lookup is O(1).
Hint 3
Recursive solutions are clean but will hit Python's default recursion limit (~1 000) on a 10⁵-node skewed tree. An explicit stack that pushes the right subtree's work before the left subtree's work processes frames in exactly preorder order without touching the call stack.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two traversals encode complementary information:
- Preorder tells you the root of every subtree first — whichever preorder value you're about to consume is the root of the window you're currently building.
- Inorder tells you the boundary between left and right subtrees — once you know the root, every value to its left in the inorder window belongs to the left subtree, and every value to its right belongs to the right subtree.
So the algorithm maintains a pointer into preorder and a window [lo, hi] into inorder. At each step:
- Consume
preorder[ptr]as the current root. - Look up its inorder index
m. - Recurse on
[lo, m-1]for the left child and[m+1, hi]for the right child.
Why naïve is O(n²)
Without preprocessing, finding m requires scanning up to n elements at each level. A fully left-skewed tree of n nodes triggers n scans for a total of O(n²) comparisons. The fix is a hash map built once in O(n) that gives O(1) lookups thereafter.
Slicing arrays instead of passing index bounds has the same problem: each slice copies up to n elements, again summing to O(n²).
Avoiding stack overflow
Python's default recursion limit is around 1 000. A skewed tree with 10⁵ nodes would blow past that. The solution below uses an explicit stack: right-subtree frames are pushed before left-subtree frames so that, when popped, work proceeds in the correct preorder order.
Input validation
Raise ValueError (rather than returning None, which is ambiguous with an empty tree) for any of the following:
| Check | What it catches |
|---|---|
len(preorder) != len(inorder) | truncated or padded arrays |
| duplicate value in inorder | ambiguous split; tree cannot be unique |
| value in preorder absent from the index map | the two arrays contain different value sets |
inorder index m falls outside the current window [lo, hi] | same values, wrong structural ordering |
The last check is the subtle one and the only one that catches structurally inconsistent orderings. For example, preorder = [1, 2, 3] and inorder = [3, 1, 2]: root 1 sits at inorder index 1, leaving window [0, 0] for the left subtree, but the next preorder value (2) maps to inorder index 2, which is outside [0, 0] — rejected.
Why these checks are sufficient: if every frame passes the range check, the constructed tree reproduces the given preorder (nodes are created in pointer order) and the given inorder (each node sits at index m between its subtrees). So the input is valid if and only if no check fails.
Complexity
- Time: O(n) — one hash-map build, one node creation per frame, O(1) work per frame.
- Space: O(n) — hash map O(n), explicit stack O(n) in the worst case.
Common mistakes
- Using array slices instead of index bounds (hidden O(n²)).
- Linear search for the inorder index instead of a hash map (same problem).
- Forgetting to push the right frame before the left frame on an explicit stack (left must be processed first, so it must be on top).
- Treating a
Nonereturn as a valid signal for bad input rather than raising explicitly.
Python implementation
from typing import Hashable, List, Optional
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(preorder: List[Hashable], inorder: List[Hashable]) -> Optional[TreeNode]:
"""Reconstruct a binary tree from preorder and inorder traversals.
Raises ValueError if the traversals are inconsistent or malformed.
Returns None for two empty arrays (empty tree).
"""
n = len(preorder)
if n != len(inorder):
raise ValueError("traversals have different lengths")
if n == 0:
return None
# Build value → inorder-index map; also detects duplicates.
index: dict = {}
for i, v in enumerate(inorder):
if v in index:
raise ValueError(f"duplicate value {v!r} in inorder")
index[v] = i
# Dummy parent so the root attaches via the same code path as any child.
dummy = TreeNode(None)
pre = 0 # pointer into preorder
# Stack frames: (lo, hi, parent_node, is_left_child)
# Right is pushed first so left is popped (processed) first.
stack = [(0, n - 1, dummy, True)]
while stack:
lo, hi, parent, is_left = stack.pop()
if lo > hi:
continue
val = preorder[pre]
pre += 1
m = index.get(val)
if m is None:
raise ValueError(f"value {val!r} in preorder is missing from inorder")
if not (lo <= m <= hi):
raise ValueError(
f"traversals are structurally inconsistent near value {val!r}"
)
node = TreeNode(val)
if is_left:
parent.left = node
else:
parent.right = node
stack.append((m + 1, hi, node, False)) # right subtree (processed later)
stack.append((lo, m - 1, node, True)) # left subtree (processed next)
return dummy.left
Unit tests
The tests round-trip through the tree: re-derive preorder and inorder from the reconstructed tree and compare them to the inputs. This is stronger than spot-checking individual node values.
import unittest
def _preorder(root):
out, stack = [], [root] if root else []
while stack:
cur = stack.pop()
out.append(cur.val)
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
return out
def _inorder(root):
out, stack, cur = [], [], root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
out.append(cur.val)
cur = cur.right
return out
class TestBuildTree(unittest.TestCase):
def roundtrip(self, pre, ino):
root = build_tree(pre, ino)
self.assertEqual(_preorder(root), pre)
self.assertEqual(_inorder(root), ino)
return root
def test_empty(self):
self.assertIsNone(build_tree([], []))
def test_single_node(self):
root = self.roundtrip([42], [42])
self.assertIsNone(root.left)
self.assertIsNone(root.right)
def test_balanced(self):
self.roundtrip([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])
def test_left_skewed(self):
# Every node has only a left child.
self.roundtrip([1, 2, 3, 4], [4, 3, 2, 1])
def test_right_skewed(self):
# Every node has only a right child; preorder == inorder.
self.roundtrip([1, 2, 3, 4], [1, 2, 3, 4])
def test_mismatched_lengths(self):
with self.assertRaises(ValueError):
build_tree([1, 2], [1])
def test_duplicate_in_inorder(self):
with self.assertRaises(ValueError):
build_tree([1, 2, 2], [2, 1, 2])
def test_structurally_inconsistent(self):
# Same values, but no tree can produce both orderings.
with self.assertRaises(ValueError):
build_tree([1, 2, 3], [3, 1, 2])
if __name__ == "__main__":
unittest.main()