Skip to content
Problem 105 · LeetCode 105(opens in a new tab)

Construct Binary Tree from Preorder and Inorder Traversal

MediumDivide and conquer

A binary tree with all-different values was walked twice. preorder lists its values root first, then the whole left subtree, then the whole right subtree. inorder lists them left subtree first, then the root, then the right subtree.

Rebuild the tree from the two lists and return its root.

Example 1

Input:  preorder = [1, 2, 4, 3, 5], inorder = [4, 2, 1, 5, 3]
Output: [1, 2, 3, 4, null, 5]
Why:    1 is the root; 4, 2 sit left of it in inorder, 5, 3 sit right
2 more examples and the constraints

Example 2

Input:  preorder = [7], inorder = [7]
Output: [7]
Why:    a single node is its own tree

Example 3

Input:  preorder = [5, 6, 8], inorder = [5, 6, 8]
Output: [5, null, 6, null, 8]
Why:    nothing is ever left of a root, so every child hangs right

Constraints

  • 1 ≤ number of nodes ≤ 3,000
  • preorder and inorder have the same length and hold the same values
  • −3,000 ≤ every value ≤ 3,000, and no value appears twice
  • Both lists come from one real tree

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion, scanning for the rootO(n²)
  2. Recursion with a position mapO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 3,000 nodes in a chainVerdict
Recursion, scanning for the rootO(n²)
Correct; slow on lopsided trees
Recursion with a position mapO(n)
Best; one lookup per node

n = number of nodes. On a balanced tree the scan is closer to O(n log n).

Edge cases to test

  • One node. [7] and [7] give a single root with no children.
  • Only right children. Preorder equals inorder; every left range is empty.
  • Only left children. Inorder is preorder reversed; the recursion is n calls deep, so watch the stack in Python.
  • Negative values. Values are labels, not positions; −3,000 works like any other key.

Common mistakes

  • Building the right subtree before the left, so the preorder pointer hands out the wrong roots.
  • Slicing new lists on every call, which quietly brings back O(n²) copying.
  • Using the root value as an index instead of looking up its inorder position.

How to talk through it

  1. 1Clarify. Are the values all different? Are both lists guaranteed to come from one tree?
  2. 2Find the root. The first preorder value is the root, and inorder splits around it into left and right.
  3. 3Give the simple recursion. Scan for the root each time; say that costs O(n²) on a chain.
  4. 4Remove the scan. A value → index map makes each split O(1), and a preorder pointer plus range bounds avoid copying.
  5. 5Test out loud. Run one node, a right-only chain and a left-only chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?