Rebuild a Search Tree from Its Preorder Listing
Trees & GraphsAuto-graded · 19 test casesLast updated
Rebuild a binary search tree from its preorder listing of distinct integers in linear time, then report it in level order with null placeholders. Tests stack-based construction and BFS serialization.
Rebuild a Search Tree from Its Preorder Listing
You are given a list of distinct integers that is the preorder traversal (node, then left subtree, then right subtree) of some binary search tree (BST). Reconstruct that exact tree and return it in level-order serialization.
In a BST, every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger.
Output format
Return a list describing the tree level by level, from left to right:
- Start with the root.
- For every real node, in level-order, append its value and then enqueue both of its children, using
Nonefor a child that does not exist. Noneentries are visited too, and they contribute aNoneto the output, but they have no children of their own.- After the traversal, remove all trailing
Nonevalues from the list. - If the input is empty, return an empty list
[].
For instance, a chain where each node only has a right child is written as [1, None, 2, None, 3], because each node's missing left child appears as None.
Notes
- Do not rebalance the tree or sort the values. The tree you return must be the one that the given preorder describes.
- The tree may be completely lopsided (a single long chain), so be careful with very deep recursion.
Task
Implement rebuild_bst_level_order(preorder) which takes the preorder list and returns the level-order serialization described above.
Constraints
0 <= len(preorder) <= 100,000- All values are unique signed 32-bit integers.
- The input is guaranteed to be a valid preorder traversal of some BST.
- An empty input returns
[].
Examples
Example 1
Input: rebuild_bst_level_order([8, 5, 1, 7, 10, 12])
Output: [8, 5, 10, 1, 7, None, 12]
Example 2
Input: rebuild_bst_level_order([1, 2, 3, 4, 5])
Output: [1, None, 2, None, 3, None, 4, None, 5]
Example 3
Input: rebuild_bst_level_order([4, 2, 1, 3, 6, 5, 7])
Output: [4, 2, 6, 1, 3, 5, 7]
Hints
Hint 1
Every value after the first must be a child of a node you have already seen. Think about which already-seen nodes can still accept a new child.
Hint 2
Keep a stack of nodes that are still waiting for a right child. If the next value is smaller than the top, it becomes the top's left child. Otherwise pop while the top is smaller than the value.
Hint 3
The last node popped is the parent of the new value (as its right child). Finally, do a BFS that also enqueues missing children as None, and strip trailing Nones from the result.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
In a preorder listing, each node appears before everything in its subtrees, so every new value is a child of a node that has already been seen. We only need to decide which one.
Maintain a stack of nodes that may still receive a right child. The stack is strictly decreasing from bottom to top. For each new value v:
- If
vis smaller than the top of the stack, it is the top's left child (a node's left subtree starts immediately after it in preorder). Attach it and push it. - Otherwise
vis larger than the top, so the top's subtree is complete. Pop while the top is smaller thanv. The last node popped is the deepest ancestor that is smaller thanv, sovbecomes its right child. Pushv.
After building the tree, run a BFS that enqueues both children of every real node, including missing ones as None, appending each visited entry to the output. Finally strip trailing None values.
Why it is correct
- Left case: if
v < top, thenvbelongs insidetop's subtree. Preorder places the left subtree directly aftertop, andtophas no left child yet, sovis that left child. - Right case:
v > topmeansvcannot be intop's left subtree. Popping removes ancestors smaller thanvin increasing order. The last one popped is the nearest ancestor whose right subtree must containv. It has no right child yet, since any earlier right child would have been pushed above it, been smaller thanv, and been popped as well. Sovis exactly its right child. - Values are unique, so the right case always pops at least once and the parent exists.
- Iteration (no recursion) means a completely skewed input of 100,000 values causes no stack overflow.
Complexity
- Time:
O(n). Each node is pushed once and popped at most once, and the BFS visits each node plus at mostn + 1Noneslots. - Space:
O(h)auxiliary for the construction stack (up toO(n)for a skewed tree), plusO(n)for the tree and output.
Reference solution
from collections import deque
from typing import List, Optional
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def rebuild_bst_level_order(preorder: List[int]) -> List[Optional[int]]:
if not preorder:
return []
root = Node(preorder[0])
stack = [root]
for value in preorder[1:]:
node = Node(value)
if value < stack[-1].value:
stack[-1].left = node
stack.append(node)
else:
parent = None
while stack and value > stack[-1].value:
parent = stack.pop()
parent.right = node
stack.append(node)
result = []
queue = deque([root])
while queue:
node = queue.popleft()
if node is None:
result.append(None)
else:
result.append(node.value)
queue.append(node.left)
queue.append(node.right)
while result and result[-1] is None:
result.pop()
return result