Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get two integer arrays from the same binary tree:
preorder: the values visited as node, then left subtree, then right subtree.inorder: the values visited as left subtree, then node, then right subtree.
Rebuild the tree and return its root. All values are unique, which is what makes the answer unique. Both arrays have the same length n, with 1 to 3,000 values.
Example: preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7] → [3, 9, 20, null, null, 15, 7].
3
/ \
9 20
/ \
15 7Start with brute force
The idea below is the only sensible one. What separates the slow and fast versions is how you carry it out. The direct version does this at every step:
- take the root from the front of the current
preorderslice; - scan the current
inorderslice to find the root's position; - copy the four sub-slices (left/right of both arrays) and recurse.
The scan and the copies cost O(size of the subtree) at every node. For a tree shaped like a chain, the sizes are n, n−1, n−2, …, about n²/2 in total. With n = 3000 that's 4.5 million element copies, plus a fresh list at every level. It passes, but it's O(n²) time and memory, and the interviewer will ask you to fix it.
Building the intuition
Look at what each traversal is good at.
Preorder puts the root first. preorder[0] = 3, so 3 is the root. No searching needed.
Inorder puts the root in the middle. Find 3 in inorder = [9, 3, 15, 20, 7]. Everything to its left, [9], is the left subtree. Everything to its right, [15, 20, 7], is the right subtree. Inorder tells you how to split.
Now each side is the same problem, just smaller. The left subtree is one node, 9. For the right subtree, which of 15, 20, 7 is the root? Look at preorder again: after the root comes the entire left subtree (9), then the entire right subtree (20, 15, 7). So the right subtree's root is 20. Split [15, 20, 7] around 20: 15 goes left, 7 goes right. Done.
Notice the pattern in preorder: the roots appear exactly in the order you'd create them, if you always build a node's left subtree completely before its right. So you don't need to slice preorder at all. Keep one pointer into it, and each time you create a node, take the next value.
Two speed-ups remove all the waste:
- A hash map from value to inorder index turns "find the root in inorder" into an O(1) lookup. Values are unique, so each one has exactly one index.
- Pass index ranges, not copies. A subtree is just
inorder[lo..hi].
The optimal approach
- Build
index_in_inorder: value → position ininorder. - Set
next_root = 0, a pointer intopreorder. - Define
build(lo, hi), which builds the subtree made ofinorder[lo..hi]:- If
lo > hi, returnnull. The range is empty. root_val = preorder[next_root], then add 1 tonext_root.mid = index_in_inorder[root_val].root.left = build(lo, mid − 1), thenroot.right = build(mid + 1, hi).- Return the root.
- If
- Return
build(0, n − 1).
The subtle detail: the order of the two recursive calls matters. Preorder lists the whole left subtree before the right one. If you build the right subtree first, next_root hands it the left subtree's roots, and the tree comes out wrong. The shared pointer only works because the recursion follows preorder exactly: root, then left, then right.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
# Values are unique, so each value has exactly one position in inorder.
index_in_inorder = {val: i for i, val in enumerate(inorder)}
next_root = 0 # preorder lists roots first, so we consume it left to right
def build(lo: int, hi: int) -> Optional[TreeNode]:
# Builds the subtree whose values are exactly inorder[lo..hi].
nonlocal next_root
if lo > hi:
return None
root_val = preorder[next_root]
next_root += 1
root = TreeNode(root_val)
mid = index_in_inorder[root_val]
# Preorder is root, then the WHOLE left subtree, then the right.
# So the left subtree must be built first, or we'd take the wrong roots.
root.left = build(lo, mid - 1)
root.right = build(mid + 1, hi)
return root
return build(0, len(inorder) - 1)class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
// Values are unique, so each value has exactly one position in inorder.
indexInInorder.clear();
for (int i = 0; i < (int)inorder.size(); i++) indexInInorder[inorder[i]] = i;
nextRoot = 0; // preorder lists roots first, so we consume it left to right
return build(preorder, 0, (int)inorder.size() - 1);
}
private:
unordered_map<int, int> indexInInorder;
int nextRoot = 0;
// Builds the subtree whose values are exactly inorder[lo..hi].
TreeNode* build(vector<int>& preorder, int lo, int hi) {
if (lo > hi) return nullptr;
int rootVal = preorder[nextRoot++];
TreeNode* root = new TreeNode(rootVal);
int mid = indexInInorder[rootVal];
// Preorder is root, then the WHOLE left subtree, then the right.
// So the left subtree must be built first, or we'd take the wrong roots.
root->left = build(preorder, lo, mid - 1);
root->right = build(preorder, mid + 1, hi);
return root;
}
};class Solution {
private Map<Integer, Integer> indexInInorder;
private int nextRoot;
public TreeNode buildTree(int[] preorder, int[] inorder) {
// Values are unique, so each value has exactly one position in inorder.
indexInInorder = new HashMap<>();
for (int i = 0; i < inorder.length; i++) indexInInorder.put(inorder[i], i);
nextRoot = 0; // preorder lists roots first, so we consume it left to right
return build(preorder, 0, inorder.length - 1);
}
// Builds the subtree whose values are exactly inorder[lo..hi].
private TreeNode build(int[] preorder, int lo, int hi) {
if (lo > hi) return null;
int rootVal = preorder[nextRoot++];
TreeNode root = new TreeNode(rootVal);
int mid = indexInInorder.get(rootVal);
// Preorder is root, then the WHOLE left subtree, then the right.
// So the left subtree must be built first, or we'd take the wrong roots.
root.left = build(preorder, lo, mid - 1);
root.right = build(preorder, mid + 1, hi);
return root;
}
}/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function (preorder, inorder) {
// Values are unique, so each value has exactly one position in inorder.
const indexInInorder = new Map();
inorder.forEach((val, i) => indexInInorder.set(val, i));
let nextRoot = 0; // preorder lists roots first, so we consume it left to right
// Builds the subtree whose values are exactly inorder[lo..hi].
const build = (lo, hi) => {
if (lo > hi) return null;
const rootVal = preorder[nextRoot++];
const root = new TreeNode(rootVal);
const mid = indexInInorder.get(rootVal);
// Preorder is root, then the WHOLE left subtree, then the right.
// So the left subtree must be built first, or we'd take the wrong roots.
root.left = build(lo, mid - 1);
root.right = build(mid + 1, hi);
return root;
};
return build(0, inorder.length - 1);
};Dry run
preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7], so the map is {9: 0, 3: 1, 15: 2, 20: 3, 7: 4}.
Call build(lo, hi) | Takes preorder[next_root] | mid | Then builds |
|---|---|---|---|
| (0, 4) | 3 | 1 | left (0, 0), right (2, 4) |
| (0, 0) | 9 | 0 | left (0, −1) → null, right (1, 0) → null |
| (2, 4) | 20 | 3 | left (2, 2), right (4, 4) |
| (2, 2) | 15 | 2 | both children null |
| (4, 4) | 7 | 4 | both children null |
next_root reaches 5 exactly when the last node is built, so every value is used once.
Complexity
- Time: O(n). Building the map is O(n). Each
buildcall that creates a node does O(1) work, and there arensuch calls, plus at mostn + 1calls that returnnull. - Space: O(n) for the hash map, plus O(h) recursion stack (up to O(n) for a chain).
Edge cases and traps
- Building right before left. The shared preorder pointer then feeds the wrong roots. Always build left first.
- Scanning inorder with
index(). That's O(n) per node and O(n²) overall. Use the map. - Slicing arrays in Python.
preorder[1:mid+1]copies. It's correct but O(n²) for skewed trees. Pass indices instead. - Duplicate values. The map, and the problem itself, need unique values. With duplicates, more than one tree can fit.
- One node.
build(0, 0)creates it, and both children arebuildcalls on empty ranges.
Say it in the interview
"preorder starts with the root, and the root's position in inorder splits the values into the left and right subtrees. So I recurse on inorder ranges. To find the split in O(1), I map each value to its inorder index. And because preorder lists roots in exactly the order I'll create them, if I build left before right, I can just walk a single pointer through preorder. Each node is O(1), so it's O(n) time and O(n) space for the map."
Follow-ups interviewers ask
- "What about inorder and postorder?" Postorder puts the root last. So walk a pointer from the end of postorder, and build the right subtree before the left, because reading postorder backwards gives root, right, left.
- "Can you rebuild from preorder and postorder?" Not always uniquely. If a node has only one child, nothing tells you whether it's a left or a right child. Inorder is what pins down left versus right.
Practise the same idea
This is Day 58 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free