KatInterview

Rebuild a Binary Tree from Pre- and In-Order Sequences

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbinary-treerecursionhash-map

Last updated

Given preorder and inorder traversal arrays of a binary tree with unique values, reconstruct the tree in O(n) time and O(n) space.

Rebuild a Binary Tree from Pre- and In-Order Sequences

You are given two integer arrays, preorder and inorder, produced by traversing the same binary tree. All node values in the tree are unique.

  • preorder[i] is the value of the i-th node visited in a preorder (root → left → right) walk.
  • inorder[i] is the value of the i-th node visited in an inorder (left → root → right) walk.

Reconstruct the tree and return its root node.

Requirements

  1. Your solution must run in O(n) time and use O(n) extra space (not counting the output tree itself). Explain why a naïve implementation falls short of O(n) and what you do to meet the target.
  2. Describe how you would validate the inputs. List the checks you would add, explain why each one is necessary, and state what your function should do when an input cannot correspond to any valid binary tree.
  3. Write unit tests covering at minimum: an empty tree, a single node, a left-skewed tree, a right-skewed tree, a balanced tree, and at least two invalid-input cases.

Function signature (Python)

def build_tree(preorder: list, inorder: list) -> TreeNode | None:
    ...

where TreeNode has the attributes val, left, and right.

Examples

preorder = [3, 9, 20, 15, 7]
inorder  = [9, 3, 15, 20, 7]

Reconstructed tree:
        3
       / \
      9  20
         / \
        15   7
preorder = [1]
inorder  = [1]
→ A single root node with no children.
preorder = [1, 2]
inorder  = [1, 2]       ← 2 is to the right of 1 in inorder
→ Root 1 with right child 2.

Constraints

  • 0 ≤ n ≤ 10^5
  • All values are unique and hashable.
  • Both arrays contain the same set of values (if valid).

Hints

Hint 1

The first element of preorder is always the root of the current subtree. Once you know the root, its position in inorder tells you exactly how many nodes belong to its left subtree versus its right subtree.

Hint 2

A linear scan to find the root's position in inorder at every level gives O(n²) on skewed trees. Store a hash map from value to inorder index before you start, so each lookup is O(1).

Hint 3

Recursive solutions are clean but will hit Python's default recursion limit (~1 000) on a 10⁵-node skewed tree. An explicit stack that pushes the right subtree's work before the left subtree's work processes frames in exactly preorder order without touching the call stack.