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:
    1. Seed a first-in, first-out queue with the reconstructed root node.
    2. 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 None to the output list without pushing anything onto the queue.
    3. After the queue empties, strip all None entries 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 preorder are pairwise distinct, and preorder and inorder always come from one valid binary tree (which may be skewed up to depth 3000).

Step-by-step walkthrough

  1. Understand the two phases: reconstruct, then serialize

    We receive two distinct-integer sequences produced by the same binary tree:

    • preorder visits Root -> Left subtree -> Right subtree.
    • inorder visits Left subtree -> Root -> Right subtree.

    The task splits into two self-contained steps:

    1. Reconstruct the unique binary tree matching preorder and inorder.
    2. Serialize that tree breadth-first (top to bottom, left to right), emitting None for any missing child of a real node and stripping trailing None markers 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 0 or negative (-10^9 to 10^9), and 3,000 nodes may form a single chain 3,000 levels deep.

  2. Key observation: preorder names the root, inorder splits left and right

    Why do these two traversals lock down the tree uniquely?

    1. Inside any subtree's preorder slice, the first element is always that subtree's root.
    2. Because all values are distinct, that root value sits at a single index split_idx inside inorder. Every entry before split_idx in inorder belongs to the left subtree, and every entry after split_idx belongs to the right subtree!
    3. Counting how many entries sit before split_idx gives left_size. Since preorder visits the entire left subtree right after the root, the next left_size entries in preorder form 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.

  3. 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:

    1. Quadratic O(n^2) runtime: On a skewed chain, .index() scans up to n items and list slicing copies up to n items at every single node (1 + 2 + ... + n = O(n^2)).
    2. RecursionError at depth 3,000: Python's default recursion limit (sys.getrecursionlimit()) is 1,000. A 3,000-node chain recurses 3,000 frames deep and crashes!
  4. Code `_rebuild` with index windows, a lookup map, and an explicit stack

    We eliminate all three issues cleanly:

    • Build inorder_index = {value: idx} once in O(n) time so finding split_idx takes O(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 tasks instead of recursion. Each entry (node, pre_start, in_start, size) carries an already-instantiated TreeNode for preorder[pre_start]. Popping an entry computes left_size = split_idx - in_start and right_size = size - 1 - left_size, links node.left / node.right whenever non-empty, and pushes child tasks onto tasks:
    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
    
  5. Code `_serialize` in level order with a deque

    For breadth-first serialization, use collections.deque so queue.popleft() runs in O(1) time (whereas list.pop(0) shifts every remaining element in O(n)):

    • Popping a None placeholder appends None to output and pushes nothing (absent nodes do not spawn child placeholders).
    • Popping an actual TreeNode appends node.value and pushes both node.left and node.right (whether TreeNode or None).
    • Once queue is empty, pop None from the back of output while output[-1] is None.

    Always test is None explicitly rather than truthiness (if not node: or while not output[-1]:), because 0 is 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
    
  6. Trace Example 2 step by step

    Let's trace preorder = [-4, 9, 0] and inorder = [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]
    
  7. 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, where n = len(preorder). Populating inorder_index scans inorder once in O(n); the explicit tasks stack processes each of the n nodes once using an O(1) dictionary lookup and integer arithmetic; and breadth-first serialization pops n real nodes plus n + 1 null child slots from a deque in O(1) each before trimming at most n + 1 trailing Nones.
  • Space: O(n). The inorder_index dictionary, the n TreeNode instances, the tasks stack (at most n tuples), the BFS deque, and the output list (at most 2n + 1 slots before trimming) all use memory linear in n.

Edge cases

  • Single-node tree ([42], [42]): left_size = 0 and right_size = 0; serialization produces [42, None, None] and strips both trailing Nones to return [42].
  • Skewed chains of depth 3,000 (all-left, all-right, or zigzag): Processed iteratively on the heap via tasks without touching Python's recursion limit.
  • Node value 0 (especially as the final leaf, as in [-4, 9, 0]): Explicit is None checks ensure 0 is never treated as a null placeholder or stripped during tail trimming.
  • Extreme integer values (-10^9 and 10^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 internal None), 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 of 1,000 raises RecursionError on skewed 3,000-node inputs.
  • Setting left_size = split_idx instead of split_idx - in_start: split_idx is a global index in inorder, so subtracting the current window's in_start is required inside every right subtree (in_start > 0).
  • Reading the right child from preorder[split_idx + 1]: split_idx + 1 marks the right subtree inside inorder; inside preorder, the right subtree begins at pre_start + 1 + left_size.
  • Serializing via heap-array positions 2i + 1 and 2i + 2: Heap indexing allocates two child slots even under None entries, contradicting the queue specification and exploding to 2^3000 slots on skewed chains.
  • Using list.pop(0) for the BFS queue: list.pop(0) shifts every remaining item in O(k) time; collections.deque.popleft() runs in O(1) time.

Alternative approaches

  • Recursive window bounds with sys.setrecursionlimit: Uses the same inorder_index map and window offsets recursively after raising Python's recursion limit past 3,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): Scan preorder while keeping a stack of ancestors whose right subtrees have not started and an index j in inorder: attach new preorder values as .left while stack[-1].value != inorder[j], then pop matching ancestors while advancing j and attach the next preorder value as .right of 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 in inorder_index yields the same left_size and right_size; inside postorder, the left subtree spans [post_start : post_start + left_size] (rooted at post_start + left_size - 1) and the right subtree spans [post_start + left_size : post_start + size - 1] (rooted at post_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] and postorder = [v, u] whether v is 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 either 0 or 2 children): whenever size > 1, preorder[pre_start + 1] must be the left child's root, and locating that value inside postorder reveals left_size immediately.

  • 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] and inorder = [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 that len(preorder) == len(inorder) == len(inorder_index) and verify on every popped task that node.value in inorder_index and in_start <= split_idx < in_start + size; any out-of-window split proves the two traversals cannot come from one tree and should raise a ValueError.

Follow-up questions

Similar questions

More StackAdapt interview questions

All 10 StackAdapt questions →