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 distinct
  • postorder is 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

  1. 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 START
    

    Notice the two engineering requirements in the problem:

    1. Strict O(n) runtime (n <= 10,000), ruling out both O(n^2) array partitioning and O(n log n) sorting.
    2. Skewed trees of height n = 10,000 (such as Example 3 extended to 10,000 nodes), which exceed Python's default 1,000-frame recursion limit if implemented recursively. Both the tree reconstruction and the preorder readout must be iterative.
  2. Why naive splitting at the root is too slow

    Because postorder visits (Left, Right, Node), postorder[-1] is always the overall root, entries < root belong to its left subtree, and entries > root belong to its right subtree.

    Why not scan postorder[:-1] to partition elements into left and right sublists and repeat? Consider a left-skewed chain postorder = [1, 2, 3, ..., 10000]:

    • Root 10000 scans 9999 elements (left has 9999, right has 0).
    • Root 9999 scans 9998 elements, and so forth.
    • Total work adds up to 9999 + 9998 + ... + 1 = O(n^2) (~50 million operations), and recursion depth hits 10,000, raising RecursionError.
  3. Key insight: read postorder backwards to meet parents before children

    Why is postorder awkward when read left to right? Because children appear before their parents (Left, Right, Node) — when we see 2 and 7, we have not yet met their parent 5.

    Look at what happens when we scan postorder backwards (from index n - 1 down to 0):

    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 -> 6
    

    Reading 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.

  4. Find each node's parent in O(1) amortized time with a monotonic stack

    As we scan backwards (Node -> Right -> Left), keep a stack of nodes whose left subtree has not started yet. Let's see how each incoming new_node attaches to stack:

    • Case 1: new_node.val > stack[-1].val (went bigger -> right child). Immediately after visiting stack[-1], the Node -> Right -> Left order enters stack[-1]'s right subtree (if non-empty). Every key in that right subtree exceeds stack[-1].val, whereas keys in stack[-1]'s left subtree (or an earlier ancestor's left subtree) are smaller. Thus new_node must be stack[-1].right! We link it and push new_node onto stack (notice stack stays 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 on stack owns new_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)
               \
               16
    
    Because `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!
    
  5. Code the linear-time BST rebuild

    Translating those two cases into TreeNode and build_from_postorder is clean and direct. Every node is pushed onto stack once 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 root
    
  6. Collect the preorder iteratively and trace Example 2

    With root rebuilt, read off its preorder (Node, Left, Right) without recursion using an explicit visit_stack: pop a node, append its key to result, then push node.right first and node.left second. Because a stack is Last-In, First-Out, pushing left second places left on 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 result
    

    Let'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]
    
  7. 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):

  1. Start at 8 (root = 8, stack = [8]), then link 8.right = 12 and 12.right = 16 (stack = [8, 12, 16]).
  2. Read 10: 10 < 16, so pop 16 and 12 (stopping at 8 < 10); last popped is 12, giving 12.left = 10 (stack = [8, 10]).
  3. Read 3: 3 < 10, so pop 10 and 8; last popped is 8, giving 8.left = 3 (stack = [3]), then 6 > 3 gives 3.right = 6.
  4. Iterative preorder (Node, Left, Right) visits 8 -> 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_postorder inspects each element once from right to left; although the inner while loop may pop several ancestors in one step, each of the n TreeNodes is pushed onto stack once and popped at most once, giving amortized O(1) time per node (meaning multi-pop steps average out to at most two stack operations per node overall). collect_preorder likewise pushes and pops each node once.
  • Space: O(n). Rebuilding the tree allocates n TreeNode instances, stack and visit_stack each hold at most n nodes (reaching n on a right-skewed chain), and result stores n integers.

Edge cases

  • Single-node tree ([42]): range(len(postorder) - 2, -1, -1) is empty, build_from_postorder returns the lone root, and collect_preorder returns [42].
  • Strictly increasing postorder (Example 3, [-5, -1, 2, 7], or 1..10000): Forms a left-only chain rooted at postorder[-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 at 1 of height 10,000; stack grows to size 10,000 with zero pops, producing [1, 2, ..., 10000].
  • Alternating zigzag chain (1 -> 10000 -> 2 -> 9999 -> ...): Reaches height 10,000 with alternating .right and .left edges; both iterative passes finish in milliseconds without recursion frames.
  • Negative keys and +-10^9 extremes: 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,000 frames, so any skewed input of 10,000 nodes raises RecursionError.
  • Linearly scanning to locate the < root / > root split index. Even an iterative scan per node degrades to O(n^2) on skewed chains, violating the O(n) bound.
  • Sorting postorder to obtain inorder. Reconstructing from inorder + postorder with a hash map takes O(n) after sorting, but sorting costs O(n log n).
  • Scanning postorder forward instead of backward. Forward postorder lists children before parents; the monotonic stack invariant only holds when parents precede children (postorder read from index n - 1 down to 0).
  • Linking .left to stack[-1] after popping instead of to the last popped node. Once all nodes > new_node.val are popped, stack[-1] (if any) is smaller than new_node.val; the true parent is the last node popped.
  • Pushing left before right in iterative preorder. Because a stack is Last-In, First-Out, push node.right first and node.left second so node.left pops first.

Alternative approaches

  • Value-bounded consumption from the back (build(lower, upper)): Consuming postorder from index n - 1 downward, the next element belongs to the active subtree if and only if lower < val < upper, building right under (val, upper) then left under (lower, val) in O(n) time. A recursive implementation hits Python's recursion limit on 10^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)): Sorting postorder recovers the BST's inorder sequence, reducing the task to classic binary-tree reconstruction from inorder and postorder — simple when O(n log n) is acceptable, but too slow when strict O(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, scan preorder forward while keeping a decreasing monotonic stack: whenever new_val < stack[-1].val, link stack[-1].left = new_node, and whenever new_val > stack[-1].val, pop all nodes < new_val and link parent.right = new_node on the last popped node. Then obtain postorder iteratively in O(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 attach parent.left = new_node, tighten upper_bound = parent.val because every remaining element in the backward scan must reside inside parent's left subtree (or an even smaller ancestor's left subtree). If any incoming key satisfies val >= upper_bound, or equals stack[-1].val after popping (indicating a duplicate), reject the input; otherwise every attached node obeys its exact (lower, upper) BST interval in one O(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 < root still form the left subtree, and keys >= root form the right subtree. In build_from_postorder, relax the right-child test from new_node.val > stack[-1].val to new_node.val >= stack[-1].val while keeping the while pop condition strictly stack[-1].val > new_node.val, so equal keys chain down .right links in O(n) time.

Follow-up questions

Similar questions

More Cubist interview questions

All 3 Cubist questions →