Construct Binary Tree from Preorder and Inorder Traversal
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
You're given two arrays describing the same binary tree, whose values are all unique:
preorder: the values in preorder (node, then left subtree, then right subtree).inorder: the values in inorder (left subtree, then node, then right subtree).
Rebuild the tree and return its root.
Understand the problem
A traversal is an order for visiting every node of a tree. These two differ only in when the node itself is written down:
| Traversal | Order | For the tree below |
|---|---|---|
| preorder | node, left subtree, right subtree | 3, 9, 20, 15, 7 |
| inorder | left subtree, node, right subtree | 9, 3, 15, 20, 7 |
3
/ \
9 20
/ \
15 7Neither list alone is enough to know the tree's shape. Together they are: your job is to work the shape back out.
Example 1
Input: preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
Output: [3, 9, 20, null, null, 15, 7]The tree drawn above.
Example 2
Input: preorder = [-1], inorder = [-1]
Output: [-1]A single node.
How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.
Constraints
1 <= preorder.length <= 3000inorder.length == preorder.length- All values are unique, and both arrays describe the same tree.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
The first preorder value is the root; finding it in inorder tells you which values are in the left subtree and which are in the right, so you build each side the same way, recursively.
The key insight
Each traversal gives you one piece of information:
- Preorder (node, left, right) always lists the root first. So
preorder[0]is the root. - Inorder (left, node, right) has the root in the middle: everything before it belongs to the left subtree, everything after it to the right subtree.
preorder = [3, 9, 20, 15, 7] → the root is 3
inorder = [9, 3, 15, 20, 7]
↑ ↑ ─────────
left root rightSo the left subtree is {9} and the right subtree is {15, 20, 7}. Each of those is the same problem, just smaller: recursion.
Making it fast
Two small tricks avoid copying arrays at every step:
- A map from value to its index in
inorder, built once. Finding where the root sits becomes instant. - One pointer into
preorder. Preorder lists nodes in exactly the order the recursion creates them (node, then all of its left subtree, then all of its right subtree), as long as we build the left side before the right side. So the next root is always simply "the next preorder value".
build(lo, hi) builds the subtree made of inorder[lo..hi]:
- If
lo > hi, the range is empty: returnnull. - Take the next preorder value as the root, and find its index
midininorder. - Left subtree =
build(lo, mid - 1), then right subtree =build(mid + 1, hi).
Step by step
preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7] (indexes 0 to 4):
| Call | Next preorder value | Its inorder index | Builds |
|---|---|---|---|
build(0, 4) | 3 | 1 | root 3; left = build(0, 0), right = build(2, 4) |
build(0, 0) | 9 | 0 | 9; both sides empty |
build(2, 4) | 20 | 3 | 20; left = build(2, 2), right = build(4, 4) |
build(2, 2) | 15 | 2 | 15; both sides empty |
build(4, 4) | 7 | 4 | 7; both sides empty |
Notice the preorder values are used in order, 3, 9, 20, 15, 7, one per call.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). Each node is created once, and each lookup in the map is O(1).
- Memory: O(n) for the map, plus O(h) for the recursion.
Common mistakes
- Building the right subtree before the left. The preorder pointer then hands out the wrong values. Left first, always.
- Slicing arrays in every call. It works, but copies data at every level: O(n²) in the worst case.
- Searching
inorderwithindexOfevery time. Also O(n) per node. Build the map once.
Going deeper
- This only works because the values are unique. With duplicates, you couldn't tell which
3in inorder is the root. - The same idea rebuilds a tree from postorder + inorder: in postorder the root is last, so you read postorder backward and build the right side first.
Reference solution
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode | null}
*/
export default function buildTree(preorder, inorder) {
// Where each value sits in inorder, so we can find a root's position instantly.
const indexOf = new Map(inorder.map((value, i) => [value, i]))
// Preorder lists the roots in exactly the order we build them (node, left, right).
let next = 0
// Build the subtree made of the values inorder[lo..hi].
function build(lo, hi) {
if (lo > hi) return null // empty range: no subtree here
const value = preorder[next++] // the next preorder value is this subtree's root
const mid = indexOf.get(value)
const node = new TreeNode(value)
// Values left of the root in inorder form the left subtree, values right of it the right.
// Build LEFT first: that's the order preorder lists them in.
node.left = build(lo, mid - 1)
node.right = build(mid + 1, hi)
return node
}
return build(0, inorder.length - 1)
}export default function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
// Where each value sits in inorder, so we can find a root's position instantly.
const indexOf = new Map(inorder.map((value, i) => [value, i]))
// Preorder lists the roots in exactly the order we build them (node, left, right).
let next = 0
// Build the subtree made of the values inorder[lo..hi].
function build(lo: number, hi: number): TreeNode | null {
if (lo > hi) return null // empty range: no subtree here
const value = preorder[next++] // the next preorder value is this subtree's root
const mid = indexOf.get(value)!
const node = new TreeNode(value)
// Values left of the root in inorder form the left subtree, values right of it the right.
// Build LEFT first: that's the order preorder lists them in.
node.left = build(lo, mid - 1)
node.right = build(mid + 1, hi)
return node
}
return build(0, inorder.length - 1)
}def build_tree(preorder: list[int], inorder: list[int]) -> TreeNode | None:
# Where each value sits in inorder, so we can find a root's position instantly.
index_of = {value: i for i, value in enumerate(inorder)}
# Preorder lists the roots in exactly the order we build them (node, left, right).
next_index = 0
# Build the subtree made of the values inorder[lo..hi].
def build(lo: int, hi: int) -> TreeNode | None:
nonlocal next_index
if lo > hi:
return None # empty range: no subtree here
value = preorder[next_index] # the next preorder value is this subtree's root
next_index += 1
mid = index_of[value]
node = TreeNode(value)
# Values left of the root in inorder form the left subtree, values right of it the right.
# Build LEFT first: that's the order preorder lists them in.
node.left = build(lo, mid - 1)
node.right = build(mid + 1, hi)
return node
return build(0, len(inorder) - 1)