Construct Binary Tree from Preorder and Inorder Traversal, explained

To rebuild a binary tree from its preorder and inorder lists, take the next preorder value as the root, find that value's position in the inorder list, and recurse: everything to its left in the inorder list forms the left subtree and everything to its right forms the right subtree. With a hash map from value to inorder position, the whole construction runs in O(n) time.

By Published 7 min read

The problem, in plain terms

Someone walked a binary tree twice and wrote down the values each time. The first list is preorder: a node, then its whole left subtree, then its whole right subtree. The second list is inorder: left subtree, then the node, then right subtree. Every value appears exactly once. From these two lists alone, reconstruct the original tree.

preorder: 7  2  9  4  6  1
inorder:  9  2  4  7  6  1

rebuilt tree:
        7
       / \
      2   6
     / \   \
    9   4   1
An example, made up for this page

Ask early whether values are unique. With duplicates, two different trees can produce the same pair of lists, so the answer is not well defined. Also confirm that both lists are always consistent, and whether an empty input should return an empty tree.

How the problem is used in interviews

This is a test of recursive thinking with index bookkeeping. Interviewers watch whether you can explain why the first preorder value is the root, how the inorder position splits the problem, and how you avoid copying arrays at every step. It also opens follow-ups: which pairs of traversals are enough to rebuild a tree (preorder with postorder alone is not, unless every node has zero or two children), and how to avoid deep recursion.

A slower starting idea

The direct translation of the idea slices lists. Take preorder[0] as the root, search the inorder list for it to get position m, then build the left subtree from the next m preorder values and the first m inorder values, and the right subtree from the rest. It is easy to get right, but every call does a linear search and copies slices, so a lopsided tree costs O(n²) time and the copies add O(n²) memory traffic.

def build_tree_slices(preorder, inorder):
    if not preorder:
        return None
    root = Node(preorder[0])
    mid = inorder.index(preorder[0])          # linear search
    root.left = build_tree_slices(preorder[1:mid + 1], inorder[:mid])
    root.right = build_tree_slices(preorder[mid + 1:], inorder[mid + 1:])
    return root
Python: the slicing version. Correct, but quadratic on a chain.

The optimal approach: index map and a moving pointer

Pattern: divide and conquer on traversal orders. Two changes remove the waste. First, build a dictionary from each value to its inorder index once, so finding the split is O(1). Second, stop slicing: pass the inorder bounds (lo and hi) of the subtree being built, and keep one shared pointer into preorder that advances each time a node is created. Because preorder lists a node before its left subtree and the left subtree before the right, building left first and then right consumes preorder in exactly the right order.

class Node:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def build_tree(preorder, inorder):
    where = {val: i for i, val in enumerate(inorder)}   # value -> inorder index
    next_root = 0                                       # position in preorder

    def build(lo, hi):              # build from inorder[lo..hi]
        nonlocal next_root
        if lo > hi:
            return None
        val = preorder[next_root]
        next_root += 1
        mid = where[val]
        node = Node(val)
        node.left = build(lo, mid - 1)    # left first: preorder lists it first
        node.right = build(mid + 1, hi)
        return node

    return build(0, len(inorder) - 1)
Python: O(n) recursion with a value-to-index map.

Trace the example. The pointer starts at 7, which sits at inorder index 3, so indices 0 to 2 (9, 2, 4) form the left subtree and 4 to 5 (6, 1) the right. Building the left side takes 2 next (index 1), which splits into 9 on its left and 4 on its right. Then the right side takes 6 (index 4), whose left range is empty and whose right range holds 1.

Without recursion: a stack version

Recursion depth equals tree height, so a tree shaped like a chain of a hundred thousand nodes would overflow Python's default limit. The iterative method walks preorder once with a stack of nodes whose right child is still open. While the top of the stack does not match the next unmatched inorder value, each new value becomes a left child. When it does match, pop every node that inorder has now finished, and attach the new value as the right child of the last one popped.

function buildTree(preorder, inorder) {
  if (preorder.length === 0) return null;
  const root = { val: preorder[0], left: null, right: null };
  const stack = [root];
  let j = 0;                                   // next unmatched inorder position
  for (let i = 1; i < preorder.length; i++) {
    const fresh = { val: preorder[i], left: null, right: null };
    let parent = stack[stack.length - 1];
    if (parent.val !== inorder[j]) {
      parent.left = fresh;                     // still descending to the left
    } else {
      while (stack.length > 0 && stack[stack.length - 1].val === inorder[j]) {
        parent = stack.pop();                  // climb back past finished nodes
        j += 1;
      }
      parent.right = fresh;                    // fresh is a right child
    }
    stack.push(fresh);
  }
  return root;
}
JavaScript: O(n) time, no recursion. Nodes are plain objects.

Each value is pushed once and popped at most once, so the loop is linear. It is harder to derive on the spot than the recursive version, so present the recursion first and offer this as the answer to a question about very deep trees.

Complexity summary

n nodes, tree height h
ApproachTimeExtra space
Slices plus linear searchO(n²) worst caseO(n²) worst case for copies
Index map plus pointer, recursiveO(n)O(n) map plus O(h) call stack
Stack-based, iterativeO(n)O(h) stack
n nodes, tree height h. Scroll sideways on a small screen.

Edge cases to try

  • Empty lists, which should return no tree.
  • A single value.
  • A chain where every node has only a left child (inorder is preorder reversed).
  • A chain where every node has only a right child (the two lists are identical).
  • Negative values, and values that are not in any sorted order (this is not a search tree).

Pitfalls

  • Building the right subtree before the left, which reads preorder values in the wrong order.
  • Off-by-one errors in the slice bounds: the left subtree takes the next m preorder values, where m is the inorder index minus lo.
  • Searching the inorder list on every call and calling the result linear.
  • Assuming the input is a binary search tree and sorting values to find the split.
  • Forgetting that duplicates make the problem ambiguous.

How to explain it out loud

Fictional example

Talking through the split on a whiteboard
Candidate
The first preorder value is always the root of the current subtree. Finding it in the inorder list tells me how many values are on its left, so I know where the left subtree ends.
Candidate
To avoid searching every time, I map each value to its inorder index first. Then I recurse on inorder ranges and keep one pointer into preorder that moves forward as I create nodes, left subtree before right.
Candidate
Every node is created once with O(1) work, so it's O(n) time and O(n) space for the map. If the tree could be very deep, I'd switch to the stack version to avoid recursion limits.

Turning a tree into a string and back is the natural companion: see Serialize and Deserialize Binary Tree, where you choose the format yourself and markers for empty children make one traversal enough. In-order traversal also drives Kth Smallest Element in a BST.

Rehearsing with Natively

Index-range problems go wrong in small ways that are easy to miss while talking. Natively can read the two traversal lists from a screenshot while you practice on Mac or Windows, suggest the split-and-recurse plan, and help you check a bound you are unsure about. Its transcript of your mock interview shows afterward whether you explained why preorder gives the root. See the AI interview assistant.

Questions people ask

How do you construct a binary tree from preorder and inorder traversal?

The next preorder value is the root of the current subtree. Its position in the inorder list splits the remaining values into the left and right subtrees, so recurse on each side, building the left subtree first.

What is the time complexity of building a tree from preorder and inorder?

O(n) time with a hash map from value to inorder index and a shared preorder pointer. The version that searches and slices lists at every step is O(n²) in the worst case.

Why must the values be distinct?

With repeated values, the root's position in the inorder list can be ambiguous, and different trees can produce the same two traversals.

Can you build the tree without recursion?

Yes. Walk preorder with a stack: new values become left children until the stack top matches the next inorder value, then pop finished nodes and attach the new value as a right child. It is O(n) and avoids deep call stacks.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP