Construct Binary Tree from Preorder and Inorder Traversal

medium

Given two integer arrays preorder and inorder — the preorder and inorder traversals of the same binary tree, where all values are unique — construct and return the binary tree.

The tree is returned in level-order (breadth-first), using null for missing children.

Hints

The first preorder value is the root of the (sub)tree.
Find the root in inorder: values before it are the left subtree, after it the right.
Hash each value to its inorder index for O(1) splits, and walk preorder with one moving pointer.

Common doubts

So the root has exactly one position in inorder; duplicates would make the left/right split ambiguous.
It turns the per-node O(n) search for the root's inorder position into an O(1) lookup, dropping total time from O(n^2) to O(n).
Root first, then the entire left subtree, then the right — exactly preorder, so a single incrementing index suffices.

Interview follow-ups

The root is postorder's LAST element; walk postorder from the back, building the right subtree before the left.
They don't determine where a single child attaches (left vs right), so the tree isn't unique in general.

Fun facts

  • The same map+pointer technique builds from inorder+postorder by consuming postorder in reverse.
  • This is the inverse of the traversals you learned first — construction is just traversal run backwards.

Asked at

AmazonMicrosoftBloomberg
Frequently Sometimes Occasionally
Example 1
Input: preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
Output: [3, 9, 20, null, null, 15, 7]
Root 3, left subtree {9}, right subtree rooted at 20 with children 15 and 7.
Example 2
Input: preorder = [-1], inorder = [-1]
Output: [-1]
A single node.
Constraints

- 1 <= preorder.length <= 3000 - inorder.length == preorder.length - -3000 <= values <= 3000 - All values are unique - preorder and inorder are traversals of the same tree

Solve this problem →