Assemble a Binary Tree from Two Traversals, Output by Level
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests whether a candidate can reconstruct a unique binary tree from its preorder and inorder sequences and serialize the result breadth-first with null markers.
You receive two integer arrays, pre and ino, representing the preorder and inorder traversals of the same binary tree. Every value in the tree is unique. Rebuild the tree and return it as a level-order list with None filling any gap where a child is absent.
Traversal Definitions
- Preorder: record the current node, recurse into the left subtree, then recurse into the right subtree.
- Inorder: recurse into the left subtree, record the current node, then recurse into the right subtree.
Because all values are distinct, the two traversals together describe exactly one tree, so your output is always unique.
How to Serialize the Result
Use a queue-based level-order scan:
- Seed the queue with the root node.
- On each step, remove the front element.
- If it is a real node, write its value to the output list, then push its left child and its right child onto the queue. Push a
Noneplaceholder for any child that does not exist. - If it is a
Noneplaceholder, writeNoneto the output list and push nothing.
- If it is a real node, write its value to the output list, then push its left child and its right child onto the queue. Push a
- Repeat until the queue is empty.
- Remove every
Nonevalue from the end of the output list before returning.Nonevalues that appear in the middle must stay, because they encode the tree's shape.
Constraints
1 <= len(pre) == len(ino) <= 3000-10^9 <= pre[i] <= 10^9; all values are distinct integers.inocontains exactly the same values aspre, and both arrays are guaranteed to be valid traversals of one binary tree.- The tree may be fully skewed, reaching a depth equal to the total number of nodes.
Examples
Example 1
Input: assemble_tree([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6])
Output: [1, 2, 3, 4, 5, None, 6]
Example 2
Input: assemble_tree([10, -2, 30], [10, 30, -2])
Output: [10, None, -2, 30]
Example 3
Input: assemble_tree([7], [7])
Output: [7]
Hints
Hint 1
The first element of the preorder array is always the root. Once you know the root, its position in the inorder array divides everything to its left into the left subtree and everything to its right into the right subtree. Build a hash map of value → inorder index up front so each lookup is O(1).
Hint 2
An iterative approach with an explicit stack avoids hitting Python's default recursion limit on a fully skewed 3000-node tree. The stack holds nodes on the current path from the root whose right child has not yet been assigned. When the next preorder value has a smaller inorder index than the stack top, it becomes that top node's left child; otherwise, pop nodes until you find the parent of the ne…
Hint 3
For the serialization pass, use a collections.deque and push explicit None sentinels for missing children — but only for real nodes, never for a None sentinel itself. After the BFS finishes, strip trailing Nones. Be careful with node values like 0: always check `x is None`, never rely on truthiness.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has two independent phases: tree reconstruction and level-order serialization.
Phase 1 — Reconstructing the tree iteratively
The preorder array gives us nodes in the order they would be "visited" if we walked the tree root-first. The inorder array tells us, for any two nodes, which one sits further left in the tree.
Hash map first. Build pos, a dictionary mapping each value to its index in ino. Every lookup during reconstruction is then O(1) instead of O(n).
Why iterative? A straightforward recursive approach is clean, but on a fully skewed tree with 3000 nodes the recursion depth hits 3000, well above CPython's default limit of around 1000. An explicit stack sidesteps the problem.
Stack invariant. The stack holds exactly the nodes on the path from the root to the most recently attached node, limited to those whose right child has not been assigned yet. The key property: their inorder positions strictly decrease from the bottom of the stack to the top.
For each successive preorder value v:
- If
pos[v] < pos[stack[-1]], thenvsits to the left of the stack's top in inorder. In preorder, a node's immediate successor is its left child when one exists — sovis the top's left child. - Otherwise,
vmust be someone's right child. Pop nodes off the stack as long as their inorder position is less thanpos[v]; each popped node's entire left subtree has already been processed. The last node popped isv's parent, andvbecomes its right child.
Push v in both cases, then move to the next preorder value.
The tree is represented by two plain dicts, left and right, mapping parent value to child value. No node class is needed.
Why this is correct. Preorder emits a node before any node in its subtrees. So the node that immediately follows u in preorder is either u's left child (if one exists) or the right child of the shallowest ancestor of u that has an unstarted right subtree. The stack contains exactly those ancestors, and inorder positions identify which one is the parent.
Phase 2 — Level-order serialization
Run a BFS with a deque. When a real node is dequeued, append its value and enqueue both children — pushing None for any missing child. When a None sentinel is dequeued, append None and enqueue nothing. After the BFS, pop trailing None values. Internal None values are kept because they convey where gaps are in the tree.
One pitfall: node values like 0 are falsy in Python. Always test x is None, never if not x.
Complexity
- Time: O(n). Building
posis O(n). Each node is pushed and popped at most once in the reconstruction loop, giving O(n) total. The BFS visits n real nodes and at most n + 1 sentinel slots. The trailing-trim pass is O(n). - Space: O(n) for
pos,left,right, the reconstruction stack, the BFS queue, and the output (at most 2n + 1 entries before trimming).
Edge cases
- Single node: the reconstruction loop body never executes; the BFS produces
[value, None, None], which trims to[value]. - Fully left-skewed tree: every step takes the left-child branch; the stack grows to n but each node is pushed and popped at most once.
- Fully right-skewed tree: every step pops one node and attaches a right child; the stack stays depth 1 throughout.
- Zero or negative values: the
is Noneguard handles them correctly.
Reference solution
from __future__ import annotations
from collections import deque
from typing import List
def assemble_tree(pre: List[int], ino: List[int]) -> List[int | None]:
n = len(pre)
# Map each value to its position in the inorder array for O(1) lookup.
pos = {v: i for i, v in enumerate(ino)}
left: dict[int, int] = {}
right: dict[int, int] = {}
root = pre[0]
# Stack holds nodes on the current root-to-frontier path whose
# right child has not been assigned yet.
stack = [root]
for k in range(1, n):
v = pre[k]
if pos[v] < pos[stack[-1]]:
# v lies to the left of the stack top in inorder, so it
# is the top's left child.
left[stack[-1]] = v
else:
# v lies to the right of one or more stack nodes.
# Pop until we find the deepest ancestor that v still
# falls to the right of; that node is v's parent.
parent = None
while stack and pos[stack[-1]] < pos[v]:
parent = stack.pop()
right[parent] = v
stack.append(v)
# Level-order serialization with explicit None sentinels.
out: list[int | None] = []
q: deque[int | None] = deque([root])
while q:
x = q.popleft()
if x is None:
out.append(None)
# Do not enqueue children for a missing node.
continue
out.append(x)
q.append(left.get(x)) # None if left child absent
q.append(right.get(x)) # None if right child absent
# Strip trailing Nones; internal Nones encode shape and must stay.
while out and out[-1] is None:
out.pop()
return out