Linear-Time BST Preorder From Postorder Sequence
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given postorder, the postorder walk (Left, Right, Node) of a non-empty Binary Search Tree (BST) containing pairwise distinct integers, reconstruct the tree and return its preorder walk (Node, Left, Right) in O(n) time.
Recall the BST ordering property: for every node u, every key stored in u's left subtree is strictly smaller than u's key, and every key stored in u's right subtree is strictly greater than u's key. Because all keys are distinct, postorder specifies a single valid BST, so the resulting preorder sequence is uniquely determined.
Implement:
def bst_preorder_from_postorder(postorder: list[int]) -> list[int]:
Your implementation must finish in linear O(n) time and handle degenerate (completely skewed) trees whose depth equals len(postorder).
Examples
Example 1
Input: postorder = [2, 7, 5, 12, 20, 15, 10]
Output: [10, 5, 2, 7, 15, 12, 20]
Node 10 sits at the root. Its left child 5 has leaves 2 and 7, and its right child 15 has leaves 12 and 20. Visiting (Node, Left, Right) yields [10, 5, 2, 7, 15, 12, 20].
Example 2
Input: postorder = [6, 3, 10, 16, 12, 8]
Output: [8, 3, 6, 12, 10, 16]
Root 8 has left child 3 (whose right child is 6) and right child 12 (with left child 10 and right child 16).
Example 3
Input: postorder = [-5, -1, 2, 7]
Output: [7, 2, -1, -5]
Root 7 has left child 2, which has left child -1, which has left child -5.
Constraints
1 <= len(postorder) <= 10^4-10^9 <= postorder[i] <= 10^9, and all entries are pairwise distinctpostorderis guaranteed to represent a valid BST (no validation is required)- Tree height can equal
len(postorder)on skewed inputs - Required time complexity:
O(n)
Step-by-step walkthrough
Understand BST ordering and the two traversals
In a Binary Search Tree (BST) with distinct keys, every node obeys one strict ordering invariant: keys in its left subtree are strictly smaller than the node, and keys in its right subtree are strictly larger.
We receive a tree's postorder walk (
Left, Right, Node) and must rebuild the tree to output its preorder walk (Node, Left, Right):Example 1 BST: 10 / \ 5 15 / \ / \ 2 7 12 20 Postorder (Left, Right, Node): [2, 7, 5, 12, 20, 15, 10] <-- root 10 sits at the VERY END Preorder (Node, Left, Right): [10, 5, 2, 7, 15, 12, 20] <-- root 10 sits at the VERY STARTNotice the two engineering requirements in the problem:
- Strict
O(n)runtime (n <= 10,000), ruling out bothO(n^2)array partitioning andO(n log n)sorting. - Skewed trees of height
n = 10,000(such as Example 3 extended to10,000nodes), which exceed Python's default1,000-frame recursion limit if implemented recursively. Both the tree reconstruction and the preorder readout must be iterative.
- Strict
Why naive splitting at the root is too slow
Because postorder visits
(Left, Right, Node),postorder[-1]is always the overall root, entries< rootbelong to its left subtree, and entries> rootbelong to its right subtree.Why not scan
postorder[:-1]to partition elements intoleftandrightsublists and repeat? Consider a left-skewed chainpostorder = [1, 2, 3, ..., 10000]:- Root
10000scans9999elements (lefthas9999,righthas0). - Root
9999scans9998elements, and so forth. - Total work adds up to
9999 + 9998 + ... + 1 = O(n^2)(~50 million operations), and recursion depth hits10,000, raisingRecursionError.
- Root
Key insight: read postorder backwards to meet parents before children
Why is
postorderawkward when read left to right? Because children appear before their parents (Left, Right, Node) — when we see2and7, we have not yet met their parent5.Look at what happens when we scan
postorderbackwards (from indexn - 1down to0):Forward postorder: [ Left Subtree ] [ Right Subtree ] [ Node ] Reversed postorder: [ Node ] [ Right Subtree (rev) ] [ Left Subtree (rev) ] Example 2 postorder: [6, 3, 10, 16, 12, 8] Read backwards: 8 -> 12 -> 16 -> 10 -> 3 -> 6Reading backwards produces
Node -> Right -> Left— a mirrored preorder! In this order, the first element (postorder[-1]) is the root, and every subsequent element attaches directly to some ancestor we have already created.Find each node's parent in O(1) amortized time with a monotonic stack
As we scan backwards (
Node -> Right -> Left), keep astackof nodes whose left subtree has not started yet. Let's see how each incomingnew_nodeattaches tostack:-
Case 1:
new_node.val > stack[-1].val(went bigger -> right child). Immediately after visitingstack[-1], theNode -> Right -> Leftorder entersstack[-1]'s right subtree (if non-empty). Every key in that right subtree exceedsstack[-1].val, whereas keys instack[-1]'s left subtree (or an earlier ancestor's left subtree) are smaller. Thusnew_nodemust bestack[-1].right! We link it and pushnew_nodeontostack(noticestackstays strictly increasing from bottom to top!). -
Case 2:
new_node.val < stack[-1].val(went smaller -> left child of an ancestor).stack[-1]has no right child, so we are climbing back up the ancestor chain to start some ancestor's left subtree. Which ancestor onstackownsnew_node?
Suppose stack holds [8, 12, 16] (8.right = 12, 12.right = 16) and new_node = 10: 8 Keys in 16's left subtree must lie in (12, 16) \ Keys in 12's left subtree must lie in (8, 12) <-- 10 fits here! 12 Keys in 8's left subtree must lie in (-inf, 8) \ 16Because `stack` is strictly increasing (`8 < 12 < 16`), `new_node` belongs as the left child of the **smallest stack node still greater than `new_node.val`**. Popping every node on `stack` with `val > new_node.val` (`pop 16`, `pop 12`, stop before `8`) makes the **last popped node** (`12`) that exact parent! And why can `16` and `12` stay popped permanently while `8` stays on `stack`? Because `16` has finished both subtrees, `12` has now started its left subtree at `10` (future keys in `(8, 12)` attach beneath `10`), and `8`'s left subtree `(-inf, 8)` still lies ahead!-
Code the linear-time BST rebuild
Translating those two cases into
TreeNodeandbuild_from_postorderis clean and direct. Every node is pushed ontostackonce and popped at most once, bounding total pops across the entire loop to<= n(O(n)time):from typing import Any, Dict, List, Optional, Set, Tuple class TreeNode: def __init__(self, val: int): self.val = val self.left: Optional["TreeNode"] = None self.right: Optional["TreeNode"] = None def build_from_postorder(postorder: List[int]) -> TreeNode: """Rebuild the BST in O(n) time by scanning postorder from back to front (root -> right -> left).""" root = TreeNode(postorder[-1]) # stack: monotonic increasing list of TreeNodes (from bottom to top) whose left subtrees # have NOT started yet, e.g. [TreeNode(8), TreeNode(12), TreeNode(16)]. stack = [root] # Walk backwards from second-to-last element down to index 0. for i in range(len(postorder) - 2, -1, -1): new_node = TreeNode(postorder[i]) if new_node.val > stack[-1].val: # Larger than the previous node: we are entering stack[-1]'s right subtree. stack[-1].right = new_node else: # Smaller than stack[-1]: we finished right subtrees and are entering an ancestor's left subtree. # Pop every ancestor larger than new_node.val; the LAST one popped is the tightest upper bound # above new_node.val, which is its exact parent in the BST. parent = stack.pop() while stack and stack[-1].val > new_node.val: parent = stack.pop() parent.left = new_node # Push new_node because its own right and left subtrees have not been built yet. stack.append(new_node) return rootCollect the preorder iteratively and trace Example 2
With
rootrebuilt, read off its preorder (Node, Left, Right) without recursion using an explicitvisit_stack: pop a node, append its key toresult, then pushnode.rightfirst andnode.leftsecond. Because a stack is Last-In, First-Out, pushingleftsecond placeslefton top so the entire left subtree is visited ahead of the right subtree!def collect_preorder(root: TreeNode) -> List[int]: """Return [node, left, right] preorder iteratively so skewed trees of height 10^4 never overflow recursion.""" result: List[int] = [] # visit_stack: LIFO stack of TreeNodes waiting to be visited. visit_stack = [root] while visit_stack: node = visit_stack.pop() result.append(node.val) # Push right child FIRST so that left child sits on top and gets popped (visited) first. if node.right is not None: visit_stack.append(node.right) if node.left is not None: visit_stack.append(node.left) return resultLet's trace Example 2 (
postorder = [6, 3, 10, 16, 12, 8]), scanning right-to-left (8, 12, 16, 10, 3, 6):Step Read Comparison vs stack[-1] Action Stack after step ---- ---- -------------------------- ------------------------------- ---------------- init 8 (last element = root) root = 8 [8] 1 12 12 > 8 8.right = 12 [8, 12] 2 16 16 > 12 12.right = 16 [8, 12, 16] 3 10 10 < 16 pop 16, pop 12 -> 12.left = 10 [8, 10] 4 3 3 < 10 pop 10, pop 8 -> 8.left = 3 [3] 5 6 6 > 3 3.right = 6 [3, 6] Rebuilt BST: 8 / \ 3 12 \ / \ 6 10 16 Iterative preorder (Node, Left, Right): pop 8 -> push 12, push 3 result = [8], visit_stack = [12, 3] pop 3 -> push 6 result = [8, 3], visit_stack = [12, 6] pop 6 result = [8, 3, 6], visit_stack = [12] pop 12 -> push 16, push 10 result = [8, 3, 6, 12], visit_stack = [16, 10] pop 10 result = [8, 3, 6, 12, 10], visit_stack = [16] pop 16 result = [8, 3, 6, 12, 10, 16]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class TreeNode: def __init__(self, val: int): self.val = val self.left: Optional["TreeNode"] = None self.right: Optional["TreeNode"] = None def build_from_postorder(postorder: List[int]) -> TreeNode: """Rebuild the BST in O(n) time by scanning postorder from back to front (root -> right -> left).""" root = TreeNode(postorder[-1]) # stack: monotonic increasing list of TreeNodes (from bottom to top) whose left subtrees # have NOT started yet, e.g. [TreeNode(8), TreeNode(12), TreeNode(16)]. stack = [root] # Walk backwards from second-to-last element down to index 0. for i in range(len(postorder) - 2, -1, -1): new_node = TreeNode(postorder[i]) if new_node.val > stack[-1].val: # Larger than the previous node: we are entering stack[-1]'s right subtree. stack[-1].right = new_node else: # Smaller than stack[-1]: we finished right subtrees and are entering an ancestor's left subtree. # Pop every ancestor larger than new_node.val; the LAST one popped is the tightest upper bound # above new_node.val, which is its exact parent in the BST. parent = stack.pop() while stack and stack[-1].val > new_node.val: parent = stack.pop() parent.left = new_node # Push new_node because its own right and left subtrees have not been built yet. stack.append(new_node) return root def collect_preorder(root: TreeNode) -> List[int]: """Return [node, left, right] preorder iteratively so skewed trees of height 10^4 never overflow recursion.""" result: List[int] = [] # visit_stack: LIFO stack of TreeNodes waiting to be visited. visit_stack = [root] while visit_stack: node = visit_stack.pop() result.append(node.val) # Push right child FIRST so that left child sits on top and gets popped (visited) first. if node.right is not None: visit_stack.append(node.right) if node.left is not None: visit_stack.append(node.left) return result def bst_preorder_from_postorder(postorder: list[int]) -> list[int]: # Phase 1: Reconstruct the unique BST in O(n) time using a monotonic stack. root = build_from_postorder(postorder) # Phase 2: Read off its preorder traversal iteratively in O(n) time. return collect_preorder(root)✅ Submit now — all tests should pass.
Intuition & how it works
In a Binary Search Tree (BST) — a binary tree where every left-subtree key is smaller than its node and every right-subtree key is larger — a postorder walk lists (Left, Right, Node), placing children ahead of their parents. Imagine assembling a company org chart from a bottom-up roll call where employees are named before their managers: reading forward, you keep encountering people whose manager has not been introduced yet. Read the roll call backwards, however, and (Left, Right, Node) flips into (Node, Right, Left) — the CEO comes first, followed by right-hand branches, then left-hand branches, so every person's manager is already on the chart!
Partitioning the list into < root and > root at each subtree fails because a skewed chain of 10,000 nodes rescans nearly the entire remaining list at every level (O(n^2) time), and recursive calls crash Python's 1,000-frame stack limit. Sorting the input to obtain the inorder sequence (O(n log n)) also exceeds the required O(n) linear-time bound.
Instead, we scan postorder from back to front while keeping a monotonic stack — a stack whose node keys stay strictly increasing from bottom to top, holding ancestors whose left subtrees have not started yet. Whenever the next key exceeds stack[-1].val, it attaches as stack[-1].right; whenever it is smaller, we pop every stack node larger than it so the last popped node (the tightest ancestor still above it) receives it as .left. Finally, an iterative stack traversal collects the preorder walk (Node, Left, Right).
Trace Example 2 (postorder = [6, 3, 10, 16, 12, 8], read backwards: 8, 12, 16, 10, 3, 6):
- Start at
8(root = 8,stack = [8]), then link8.right = 12and12.right = 16(stack = [8, 12, 16]). - Read
10:10 < 16, so pop16and12(stopping at8 < 10); last popped is12, giving12.left = 10(stack = [8, 10]). - Read
3:3 < 10, so pop10and8; last popped is8, giving8.left = 3(stack = [3]), then6 > 3gives3.right = 6. - Iterative preorder (
Node, Left, Right) visits8 -> 3 -> 6 -> 12 -> 10 -> 16, returning[8, 3, 6, 12, 10, 16].
Complexity
Let n = len(postorder) be the number of nodes (1 <= n <= 10^4).
- Time:
O(n).build_from_postorderinspects each element once from right to left; although the innerwhileloop may pop several ancestors in one step, each of thenTreeNodes is pushed ontostackonce and popped at most once, giving amortizedO(1)time per node (meaning multi-pop steps average out to at most two stack operations per node overall).collect_preorderlikewise pushes and pops each node once. - Space:
O(n). Rebuilding the tree allocatesnTreeNodeinstances,stackandvisit_stackeach hold at mostnnodes (reachingnon a right-skewed chain), andresultstoresnintegers.
Edge cases
- Single-node tree (
[42]):range(len(postorder) - 2, -1, -1)is empty,build_from_postorderreturns the lone root, andcollect_preorderreturns[42]. - Strictly increasing postorder (Example 3,
[-5, -1, 2, 7], or1..10000): Forms a left-only chain rooted atpostorder[-1]; each step pops 1 node and attaches.left, reversing the sequence with zero recursion. - Strictly decreasing postorder (
[10000, ..., 2, 1]): Forms a right-only chain rooted at1of height10,000;stackgrows to size10,000with zero pops, producing[1, 2, ..., 10000]. - Alternating zigzag chain (
1 -> 10000 -> 2 -> 9999 -> ...): Reaches height10,000with alternating.rightand.leftedges; both iterative passes finish in milliseconds without recursion frames. - Negative keys and
+-10^9extremes: Only<and>key comparisons are performed, so negative and extreme integers behave identically to positive ones.
Common mistakes
- Writing recursive rebuild or recursive preorder helpers. Python's default call-stack limit is
1,000frames, so any skewed input of10,000nodes raisesRecursionError. - Linearly scanning to locate the
< root/> rootsplit index. Even an iterative scan per node degrades toO(n^2)on skewed chains, violating theO(n)bound. - Sorting
postorderto obtaininorder. Reconstructing frominorder + postorderwith a hash map takesO(n)after sorting, but sorting costsO(n log n). - Scanning
postorderforward instead of backward. Forward postorder lists children before parents; the monotonic stack invariant only holds when parents precede children (postorderread from indexn - 1down to0). - Linking
.lefttostack[-1]after popping instead of to the last popped node. Once all nodes> new_node.valare popped,stack[-1](if any) is smaller thannew_node.val; the true parent is the last node popped. - Pushing
leftbeforerightin iterative preorder. Because a stack is Last-In, First-Out, pushnode.rightfirst andnode.leftsecond sonode.leftpops first.
Alternative approaches
- Value-bounded consumption from the back (
build(lower, upper)): Consumingpostorderfrom indexn - 1downward, the next element belongs to the active subtree if and only iflower < val < upper, buildingrightunder(val, upper)thenleftunder(lower, val)inO(n)time. A recursive implementation hits Python's recursion limit on10^4-node chains, though its frames can be simulated iteratively on an explicit(node, side, lower, upper)stack. - Inorder + postorder via sorting (
O(n log n)): Sortingpostorderrecovers the BST'sinordersequence, reducing the task to classic binary-tree reconstruction frominorderandpostorder— simple whenO(n log n)is acceptable, but too slow when strictO(n)is required.
Follow-up questions
- How would you invert this algorithm to convert a BST's preorder sequence into its postorder sequence in O(n) time? Use the exact mirror image! Because
preorder(Node, Left, Right) already lists parents ahead of children from left to right, scanpreorderforward while keeping a decreasing monotonic stack: whenevernew_val < stack[-1].val, linkstack[-1].left = new_node, and whenevernew_val > stack[-1].val, pop all nodes< new_valand linkparent.right = new_nodeon the last popped node. Then obtain postorder iteratively inO(n)time by running a mirrored(Node, Right, Left)stack walk and reversing the collected list at the end. - Suppose the input list might not come from any valid BST—how can you detect invalid sequences in O(n) time? Maintain an
upper_bound = float("inf")ceiling during the backward scan: whenever ancestors are popped to attachparent.left = new_node, tightenupper_bound = parent.valbecause every remaining element in the backward scan must reside insideparent's left subtree (or an even smaller ancestor's left subtree). If any incoming key satisfiesval >= upper_bound, or equalsstack[-1].valafter popping (indicating a duplicate), reject the input; otherwise every attached node obeys its exact(lower, upper)BST interval in oneO(n)pass. - If duplicate keys are permitted under the rule left < node <= right, does the backward stack reconstruction still work? Yes —
postorder[-1]is still unambiguously the root, keys strictly< rootstill form the left subtree, and keys>= rootform the right subtree. Inbuild_from_postorder, relax the right-child test fromnew_node.val > stack[-1].valtonew_node.val >= stack[-1].valwhile keeping thewhilepop condition strictlystack[-1].val > new_node.val, so equal keys chain down.rightlinks inO(n)time.
Follow-up questions
- How would you invert this algorithm to convert a BST's preorder sequence into its postorder sequence in O(n) time?
- Suppose the input list might not come from any valid BST—how can you detect invalid sequences in O(n) time?
- If duplicate keys are permitted under the rule left < node <= right, does the backward stack reconstruction still work?
Similar questions
- Thread-Safe Dependency Job Scheduler and Status Tracker
- Event-Driven Strategy Execution Framework for Quantitative Teams
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance