InterviewPrepKit

Home / Coding / Trees

Construct Binary Tree from Preorder and Inorder Traversal

medium Original ↗
Solving tips
  • Recognize this as divide-and-conquer: preorder[0] is always the root, and its position in inorder splits the remaining values into left- and right-subtree ranges.
  • Precompute a value to inorder-index hash map once so you locate each root in O(1); this is what turns the naive O(n^2) into O(n) time, O(n) space.
  • Pass index ranges (or use one global preorder pointer advancing left-then-right) instead of slicing arrays, which reintroduces O(n^2) copying.
  • Pitfall: the off-by-one when splitting preorder — the left range starts at pre_lo+1 (skip the root), and its size equals the count of inorder values left of the root.

Problem

You are given two integer arrays for the same binary tree: preorder (values in preorder-traversal order) and inorder (values in inorder-traversal order). All values are distinct. Reconstruct the tree and return its root.

Recall: preorder visits node, left subtree, right subtree; inorder visits left subtree, node, right subtree.

Examples

Example 1

Input:  preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
Output: the tree

        3
       / \
      9   20
         /  \
        15   7

The first preorder value (3) is the root; in inorder, [9] sits left of 3 (left subtree) and [15, 20, 7] sits right (right subtree).

Example 2

Input:  preorder = [-1], inorder = [-1]
Output: single node -1

One element, one node.

Example 3

Input:  preorder = [1, 2, 3], inorder = [3, 2, 1]
Output: a left-leaning chain: 1's left child is 2, 2's left child is 3

Root 1 sits at the end of inorder, so everything is in its left subtree; recursing repeats the shape.

Constraints

  • 1 <= preorder.length <= 3000, inorder.length == preorder.length
  • -3000 <= values <= 3000, all values distinct
  • Both arrays are valid traversals of one tree.
  • Expected complexity: O(n) time with a hash map; naive slicing is O(n^2).

Think about it first

Hint 1 What does the very first element of `preorder` tell you, with zero work?
Hint 2 Locate that root value in `inorder`. Its index splits `inorder` into left-subtree values and right-subtree values — and the count of left values tells you where `preorder` splits too.
Hint 3 Recurse on the two halves. For `O(n)`: build a value→index map of `inorder` once, and consume `preorder` left-to-right with a single moving pointer (build left subtree before right), so you never search or slice.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.