Level-Order Tree Reconstruction from Preorder and Inorder
Medium · Coding & Algorithms · Machine Learning Engineer · Onsite
Problem Statement
Given two integer lists preorder and inorder describing a binary tree whose node values are all distinct, recover that tree and return its compact breadth-first (level-order) representation:
def build_tree(preorder: list[int], inorder: list[int]) -> list[int | None]:
Traversal and output rules:
- Preorder order: visit the current node first, then recursively visit its left subtree, and finally its right subtree.
- Inorder order: recursively visit the left subtree first, then visit the current node, and finally its right subtree.
- Because no two nodes share the same integer value, only one binary tree can produce both sequences.
- Breadth-first serialization:
- Seed a first-in, first-out queue with the reconstructed root node.
- While the queue is non-empty, pop its front entry:
- For an actual node, append its integer value to the output list and push both its left child slot and right child slot onto the back of the queue (using a null placeholder whenever a child is missing).
- For a null placeholder, append
Noneto the output list without pushing anything onto the queue.
- After the queue empties, strip all
Noneentries from the tail of the output list so the final element is an integer value.
Examples
Example 1
Input: preorder = [8, 3, 5, 12, 9, 15], inorder = [3, 5, 8, 9, 12, 15]
Output: [8, 3, 12, None, 5, 9, 15]
Walk-through: Root 8 has left child 3 (which has no left child and right child 5) and right child 12 (with children 9 and 15). Node 3's missing left child emits an internal None, while all None placeholders below leaves 5, 9, and 15 are stripped from the end.
Example 2
Input: preorder = [-4, 9, 0], inorder = [9, 0, -4]
Output: [-4, 9, None, None, 0]
Walk-through: Root -4 has left child 9 and an absent right child (None); node 9 has an absent left child (None) and right child 0. Notice 0 is a genuine node value rather than an empty slot, so it stays at the end while 0's own two empty children are trimmed.
Example 3
Input: preorder = [42], inorder = [42]
Output: [42]
Walk-through: A single leaf node 42 enqueues two empty child placeholders whose None entries are immediately trimmed from the tail.
Constraints
1 <= len(preorder) == len(inorder) <= 3000-10^9 <= preorder[i], inorder[i] <= 10^9- All values in
preorderare pairwise distinct, andpreorderandinorderalways come from one valid binary tree (which may be skewed up to depth3000).
Step-by-step walkthrough
Understand the two phases: reconstruct, then serialize
We receive two distinct-integer sequences produced by the same binary tree:
preordervisits Root -> Left subtree -> Right subtree.inordervisits Left subtree -> Root -> Right subtree.
The task splits into two self-contained steps:
- Reconstruct the unique binary tree matching
preorderandinorder. - Serialize that tree breadth-first (top to bottom, left to right), emitting
Nonefor any missing child of a real node and stripping trailingNonemarkers from the end:
Example 1 tree: Queue output before trimming: 8 [8, 3, 12, None, 5, 9, 15, None, None, None, None, None, None] / \ 3 12 After trimming trailing Nones: \ / \ [8, 3, 12, None, 5, 9, 15] 5 9 15 (notice the internal None for 3's missing left child stays!)Keep two constraints front and center: node values can be
0or negative (-10^9to10^9), and3,000nodes may form a single chain3,000levels deep.Key observation: preorder names the root, inorder splits left and right
Why do these two traversals lock down the tree uniquely?
- Inside any subtree's
preorderslice, the first element is always that subtree's root. - Because all values are distinct, that root value sits at a single index
split_idxinsideinorder. Every entry beforesplit_idxininorderbelongs to the left subtree, and every entry aftersplit_idxbelongs to the right subtree! - Counting how many entries sit before
split_idxgivesleft_size. Sincepreordervisits the entire left subtree right after the root, the nextleft_sizeentries inpreorderform the left subtree's preorder sequence, followed immediately by the right subtree's preorder sequence:
Example 1: preorder = [ 8 | 3, 5 | 12, 9, 15 ] ^ \__/ \_______/ root left(2) right(3) inorder = [ 3, 5 | 8 | 9, 12, 15 ] \__/ ^ \_______/ left(2) root right(3)Repeating that split on each non-empty side wires up every parent-child link in the tree.
- Inside any subtree's
Why naive recursive slicing crashes on skewed trees
A quick recursive prototype that calls
.index()and slices lists at each step looks short on paper:naive_build(pre, ino): if not pre: return None root = TreeNode(pre[0]) k = ino.index(root.value) root.left = naive_build(pre[1 : 1 + k], ino[:k]) root.right = naive_build(pre[1 + k :], ino[k + 1 :])It breaks in two ways:
- Quadratic
O(n^2)runtime: On a skewed chain,.index()scans up tonitems and list slicing copies up tonitems at every single node (1 + 2 + ... + n = O(n^2)). RecursionErrorat depth 3,000: Python's default recursion limit (sys.getrecursionlimit()) is1,000. A3,000-node chain recurses3,000frames deep and crashes!
- Quadratic
Code `_rebuild` with index windows, a lookup map, and an explicit stack
We eliminate all three issues cleanly:
- Build
inorder_index = {value: idx}once inO(n)time so findingsplit_idxtakesO(1). - Track integer window offsets
(pre_start, in_start, size)rather than copying sublists:
preorder window: [ pre_start | pre_start + 1 ... | pre_start + 1 + left_size ... ] root left_size right_size inorder window: [ in_start ... (split_idx - 1) | split_idx | (split_idx + 1) ... ] left_size root right_size- Drive construction with an explicit stack list
tasksinstead of recursion. Each entry(node, pre_start, in_start, size)carries an already-instantiatedTreeNodeforpreorder[pre_start]. Popping an entry computesleft_size = split_idx - in_startandright_size = size - 1 - left_size, linksnode.left/node.rightwhenever non-empty, and pushes child tasks ontotasks:
class TreeNode: def __init__(self, value: int): self.value = value self.left: Optional["TreeNode"] = None self.right: Optional["TreeNode"] = None def _rebuild(preorder: list[int], inorder: list[int]) -> TreeNode: inorder_index: Dict[int, int] = {} for idx, value in enumerate(inorder): inorder_index[value] = idx root = TreeNode(preorder[0]) tasks = [(root, 0, 0, len(preorder))] while tasks: node, pre_start, in_start, size = tasks.pop() split_idx = inorder_index[node.value] left_size = split_idx - in_start right_size = size - 1 - left_size if left_size > 0: left_root_val = preorder[pre_start + 1] node.left = TreeNode(left_root_val) tasks.append((node.left, pre_start + 1, in_start, left_size)) if right_size > 0: right_pre_start = pre_start + 1 + left_size right_root_val = preorder[right_pre_start] node.right = TreeNode(right_root_val) tasks.append((node.right, right_pre_start, split_idx + 1, right_size)) return root- Build
Code `_serialize` in level order with a deque
For breadth-first serialization, use
collections.dequesoqueue.popleft()runs inO(1)time (whereaslist.pop(0)shifts every remaining element inO(n)):- Popping a
Noneplaceholder appendsNonetooutputand pushes nothing (absent nodes do not spawn child placeholders). - Popping an actual
TreeNodeappendsnode.valueand pushes bothnode.leftandnode.right(whetherTreeNodeorNone). - Once
queueis empty, popNonefrom the back ofoutputwhileoutput[-1] is None.
Always test
is Noneexplicitly rather than truthiness (if not node:orwhile not output[-1]:), because0is a valid integer node value!def _serialize(root: TreeNode) -> list[int | None]: output: list[int | None] = [] queue = deque([root]) while queue: node = queue.popleft() if node is None: output.append(None) continue output.append(node.value) queue.append(node.left) queue.append(node.right) while output and output[-1] is None: output.pop() return output- Popping a
Trace Example 2 step by step
Let's trace
preorder = [-4, 9, 0]andinorder = [9, 0, -4]:Phase 1: _rebuild inorder_index = {9: 0, 0: 1, -4: 2} root = TreeNode(-4), tasks = [(Node(-4), pre=0, in=0, size=3)] 1. Pop (Node(-4), pre=0, in=0, size=3): split_idx = 2 -> left_size = 2 - 0 = 2, right_size = 3 - 1 - 2 = 0 Node(-4).left = Node(preorder[1] = 9) push (Node(9), pre=1, in=0, size=2) 2. Pop (Node(9), pre=1, in=0, size=2): split_idx = 0 -> left_size = 0 - 0 = 0, right_size = 2 - 1 - 0 = 1 right_pre_start = 1 + 1 + 0 = 2 -> Node(9).right = Node(preorder[2] = 0) push (Node(0), pre=2, in=1, size=1) 3. Pop (Node(0), pre=2, in=1, size=1): split_idx = 1 -> left_size = 0, right_size = 0 (leaf!) Rebuilt tree: -4 / 9 \ 0 Phase 2: _serialize queue = [Node(-4)] - pop Node(-4) -> output=[-4], queue=[Node(9), None] - pop Node(9) -> output=[-4, 9], queue=[None, None, Node(0)] - pop None -> output=[-4, 9, None], queue=[None, Node(0)] - pop None -> output=[-4, 9, None, None], queue=[Node(0)] - pop Node(0) -> output=[-4, 9, None, None, 0], queue=[None, None] - pop 2 Nones -> output=[-4, 9, None, None, 0, None, None] Trim trailing Nones -> [-4, 9, None, None, 0]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque class TreeNode: def __init__(self, value: int): self.value = value self.left: Optional["TreeNode"] = None self.right: Optional["TreeNode"] = None def _rebuild(preorder: list[int], inorder: list[int]) -> TreeNode: """Rebuild the binary tree iteratively in O(n) time without deep recursion.""" # inorder_index: {node_value: index_in_inorder} for O(1) split lookups (all values are distinct). inorder_index: Dict[int, int] = {} for idx, value in enumerate(inorder): inorder_index[value] = idx root = TreeNode(preorder[0]) # tasks: explicit stack of (node, pre_start, in_start, size) tuples. # `node` is the already-created root of the subtree spanning: # preorder[pre_start : pre_start + size] and inorder[in_start : in_start + size]. # Using an explicit stack avoids Python's ~1000-frame RecursionError on 3000-deep skewed trees. tasks = [(root, 0, 0, len(preorder))] while tasks: node, pre_start, in_start, size = tasks.pop() # Locate `node.value` inside its inorder window to count left vs. right subtree sizes. split_idx = inorder_index[node.value] left_size = split_idx - in_start right_size = size - 1 - left_size # Left subtree starts right after the root in preorder (`pre_start + 1`) # and at the start of the current window in inorder (`in_start`). if left_size > 0: left_root_val = preorder[pre_start + 1] node.left = TreeNode(left_root_val) tasks.append((node.left, pre_start + 1, in_start, left_size)) # Right subtree starts after the root AND all `left_size` left-subtree nodes in preorder, # and right after `split_idx` in inorder (`split_idx + 1`). if right_size > 0: right_pre_start = pre_start + 1 + left_size right_root_val = preorder[right_pre_start] node.right = TreeNode(right_root_val) tasks.append((node.right, right_pre_start, split_idx + 1, right_size)) return root def _serialize(root: TreeNode) -> list[int | None]: """Serialize the tree in level order with None for missing children, trimming trailing Nones.""" output: list[int | None] = [] # queue: FIFO deque of TreeNode | None for O(1) popleft during breadth-first traversal. queue = deque([root]) while queue: node = queue.popleft() # Check `is None` explicitly (never `if not node`, because 0 is a valid node value). if node is None: output.append(None) continue output.append(node.value) # Enqueue both child slots (even if None) so missing internal children get `None` markers. queue.append(node.left) queue.append(node.right) # Trim every trailing `None` marker at the end of the level-order output. while output and output[-1] is None: output.pop() return output def build_tree(preorder: list[int], inorder: list[int]) -> list[int | None]: if not preorder: return [] root = _rebuild(preorder, inorder) return _serialize(root)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine reconstructing an org chart where every manager has at most a left team and a right team from two roll-call sheets. Preorder traversal—visiting a node first, then its entire left subtree, then its entire right subtree—always lists the top manager first, so preorder[0] immediately identifies the root. Inorder traversal—visiting the entire left subtree, then the node, then the entire right subtree—places that manager right between everyone in their left team and everyone in their right team! Finding the manager's index inside inorder instantly reveals the exact headcount of the left team (left_size) and right team (right_size), letting us partition both arrays into matching subproblems until every pointer is connected, and then read out the tree with breadth-first search (BFS) / level-order traversal (scanning level by level from top to bottom, left to right, through a queue).
A textbook recursive draft that calls inorder.index(root_val) and slices sublists like preorder[1 : 1 + k] at every node runs in O(n^2) time because linear searches and slice copies touch up to n elements per level. Even worse, on a skewed tree (a lopsided chain of n nodes descending down one path like a linked list) of 3,000 nodes, recursion stacks 3,000 frames and triggers Python's default 1,000-frame RecursionError. Precomputing an O(1) dictionary inorder_index, passing integer window bounds (pre_start, in_start, size), and managing pending subtrees on an explicit tasks stack runs in O(n) time with zero risk of stack overflow.
Walk through Example 2 (preorder = [-4, 9, 0], inorder = [9, 0, -4]):
- Root -4: First in preorder (-4), located at index 2 in inorder ([9, 0 | -4]). That puts 2 nodes in the left subtree (starting at preorder[1] = 9, so -4.left = 9) and 0 nodes on the right.
- Node 9: Located at index 0 inside inorder[0:2] = [9, 0], giving left_size = 0 and right_size = 1 ([0]), so 9.right = 0.
- Breadth-first serialization: Scanning with a deque (a double-ended queue supporting O(1) back appends and O(1) front pops) emits [-4, 9, None, None, 0, None, None], which trims trailing Nones while keeping 0 intact to return [-4, 9, None, None, 0].
Complexity
- Time:
O(n)on average, wheren = len(preorder). Populatinginorder_indexscansinorderonce inO(n); the explicittasksstack processes each of thennodes once using anO(1)dictionary lookup and integer arithmetic; and breadth-first serialization popsnreal nodes plusn + 1null child slots from adequeinO(1)each before trimming at mostn + 1trailingNones. - Space:
O(n). Theinorder_indexdictionary, thenTreeNodeinstances, thetasksstack (at mostntuples), the BFSdeque, and theoutputlist (at most2n + 1slots before trimming) all use memory linear inn.
Edge cases
- Single-node tree (
[42],[42]):left_size = 0andright_size = 0; serialization produces[42, None, None]and strips both trailingNones to return[42]. - Skewed chains of depth
3,000(all-left, all-right, or zigzag): Processed iteratively on the heap viataskswithout touching Python's recursion limit. - Node value
0(especially as the final leaf, as in[-4, 9, 0]): Explicitis Nonechecks ensure0is never treated as a null placeholder or stripped during tail trimming. - Extreme integer values (
-10^9and10^9): Values serve as hash-map keys rather than array indices, requiring no extra range allocation. - Absent left child vs. absent right child:
[1, 2]with[1, 2](right child) serializes to[1, None, 2](retaining the internalNone), whereas[1, 2]with[2, 1](left child) serializes to[1, 2].
Common mistakes
- Recursing directly without handling depth
3,000: CPython's default recursion limit of1,000raisesRecursionErroron skewed 3,000-node inputs. - Setting
left_size = split_idxinstead ofsplit_idx - in_start:split_idxis a global index ininorder, so subtracting the current window'sin_startis required inside every right subtree (in_start > 0). - Reading the right child from
preorder[split_idx + 1]:split_idx + 1marks the right subtree insideinorder; insidepreorder, the right subtree begins atpre_start + 1 + left_size. - Serializing via heap-array positions
2i + 1and2i + 2: Heap indexing allocates two child slots even underNoneentries, contradicting the queue specification and exploding to2^3000slots on skewed chains. - Using
list.pop(0)for the BFS queue:list.pop(0)shifts every remaining item inO(k)time;collections.deque.popleft()runs inO(1)time.
Alternative approaches
- Recursive window bounds with
sys.setrecursionlimit: Uses the sameinorder_indexmap and window offsets recursively after raising Python's recursion limit past3,000. Concise, though mutating interpreter-wide stack limits is less clean than an explicit stack. - One-pass ancestor stack without a hash map (
O(n)time,O(n)space): Scanpreorderwhile keeping a stack of ancestors whose right subtrees have not started and an indexjininorder: attach new preorder values as.leftwhilestack[-1].value != inorder[j], then pop matching ancestors while advancingjand attach the next preorder value as.rightof the last popped node.
Follow-up questions
-
How does the reconstruction change when the inputs are postorder and inorder traversals instead? Postorder traversal visits Left subtree -> Right subtree -> Root, placing each subtree's root at the final slot of its postorder window (
post_start + size - 1) rather than the first. Looking up that value ininorder_indexyields the sameleft_sizeandright_size; insidepostorder, the left subtree spans[post_start : post_start + left_size](rooted atpost_start + left_size - 1) and the right subtree spans[post_start + left_size : post_start + size - 1](rooted atpost_start + size - 2). -
Under what conditions can a binary tree be uniquely recovered from preorder and postorder traversals without inorder? General binary trees cannot be uniquely recovered because a parent with a single child produces identical
preorder = [u, v]andpostorder = [v, u]whethervis a left child ([u, v]) or a right child ([u, None, v]). Uniqueness holds when the tree is guaranteed to be a full binary tree (every node has either0or2children): wheneversize > 1,preorder[pre_start + 1]must be the left child's root, and locating that value insidepostorderrevealsleft_sizeimmediately. -
What breaks if duplicate node values are allowed, and how would you detect invalid or mismatched traversal arrays? Duplicate values destroy uniqueness—
preorder = [5, 5]andinorder = [5, 5]matches both a left-child tree and a right-child tree unless nodes carry distinct tie-breaking IDs. To validate untrusted arrays claiming distinct values, check upfront thatlen(preorder) == len(inorder) == len(inorder_index)and verify on every popped task thatnode.value in inorder_indexandin_start <= split_idx < in_start + size; any out-of-window split proves the two traversals cannot come from one tree and should raise aValueError.
Follow-up questions
- How does the reconstruction change when the inputs are postorder and inorder traversals instead?
- Under what conditions can a binary tree be uniquely recovered from preorder and postorder traversals without inorder?
- What breaks if duplicate node values are allowed, and how would you detect invalid or mismatched traversal arrays?
Similar questions
- Hash Map Lookup and Key-Extraction Complexity Analysis
- Sliding-Window Expiring Key-Value Map
- Running Median of an Integer Stream
- Two-Flip Fair Coin Conditional Probabilities
- Optimal Desert Banana Transport with Relay Depots
- Hierarchical Recipe and Pantry Fulfillment Service
More StackAdapt interview questions
- Hierarchical Recipe and Pantry Fulfillment Service Easy
- Sliding-Window Expiring Key-Value Map Easy
- Hash Map Lookup and Key-Extraction Complexity Analysis Medium Pro
- Two-Flip Fair Coin Conditional Probabilities Easy Pro
- Optimal Desert Banana Transport with Relay Depots Medium Pro
- Mean vs. Median of the Geometric Distribution Easy Pro
- Auditing Methodological Flaws in an ML Pipeline Report Medium Pro
- Running Median of an Integer Stream Easy Pro
- Single-Pass Uniform k-Item Reservoir Sampling Medium Pro