Rebuild the Escape Room Clues
An escape room runs on numbered clue cards. Solving a card opens at most two more, a left card and a right card, so the layout is a binary tree. The file holding it is corrupted, and two printouts survived: one lists the cards as "card, then everything on its left, then everything on its right", the other as "everything on the left, then the card, then everything on the right". Rebuild the tree exactly.
Your task
Write rebuildTree(preorder, inorder). preorder is the pre-order traversal of a binary tree (node, left subtree, right subtree) and inorder is its in-order traversal (left subtree, node, right subtree). Build the tree and return its root.
All card numbers are different, and both lists always come from the same tree, so the answer is unique. The tree is not a search tree. Empty lists mean an empty tree. Return the root as a real TreeNode. Results are shown in level order, with null for a missing child.
rebuildTree(preorder: int[], inorder: int[]) → TreeNode
Examples
preorder = [4, 7, 2, 1, 6] inorder = [7, 2, 4, 6, 1]
[4, 7, 1, null, 2, 6]
Pre-order starts with 4, so 4 is the root. In in-order, 7 and 2 come before 4 (left side) and 6 and 1 after (right side). On the left, pre-order puts 7 first and in-order puts 2 after 7, so 2 is 7's right card. On the right, 1 comes first and 6 is before it, so 6 is 1's left card.
preorder = [1, 2] inorder = [1, 2]
[1, null, 2]
Pre-order alone says 1 then 2, which fits 2 being on either side. In-order puts nothing before 1, so 1's left side is empty and 2 must be its right card.
Constraints
- 0 ≤ preorder.length = inorder.length ≤ 1,000
- -100,000 ≤ card number ≤ 100,000, all different
- Both lists hold the same numbers and describe one valid tree.
- The tree is at most 500 levels deep.
Start with brute force
Take the root from the front of pre-order, scan in-order to find it, slice both lists into left and right copies, and recurse. The idea is right, but each level scans and copies. For a chain of 1,000 cards that is about 1,000 + 999 + … + 1 ≈ 500,000 copies, O(n²). A position map removes the scans; index ranges instead of slices remove the copies.
Hints
0 of 4 shown- Hint 1
Look at the first pre-order number. Which card is it, always? Find it in the in-order list. What do the numbers on either side of it tell you?
- Hint 2
The first pre-order number is the root. In in-order, everything before it is the left subtree and everything after is the right. That also gives you the left subtree's size.
- Hint 3
Pre-order lists the root, the whole left subtree, then the whole right subtree. Knowing the left size, you can cut pre-order into those parts and solve each the same way. How do you find the root in in-order without scanning every time?
- Hint 4
Store each value's in-order position in a hash map. Recurse on an in-order range
[lo, hi], reading pre-order with one shared index that only moves forward: take the next value as the root, look up its positionm, build the left from[lo, m - 1], then the right from[m + 1, hi]. An empty range is null. Build left before right, because that is pre-order's order.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
Pre-order tells you who is the root of a subtree: whoever comes first. In-order tells you who is on which side of it. Use both, one subtree at a time.
Trace preorder = [4, 7, 2, 1, 6], inorder = [7, 2, 4, 6, 1]. In-order positions: 7→0, 2→1, 4→2, 6→3, 1→4.
build(0, 4): next pre-order value 4, at position 2. Left range 0..1, right 3..4.build(0, 1): next value 7, at position 0. Left 0..-1 is empty; right is 1..1.build(1, 1): next value 2, a leaf: 7's right child.build(3, 4): next value 1, at position 4. Left 3..3; right 5..4 is empty.build(3, 3): next value 6, a leaf: 1's left child.
The result is [4, 7, 1, null, 2, 6]. The shared pre-order index never needs computing: since each left subtree is finished before its right one, it always points at the next root.
function rebuildTree(preorder, inorder) {
const position = new Map(); // value -> index in inorder
inorder.forEach((v, i) => position.set(v, i));
let next = 0; // next unused value in preorder
// Build the subtree whose values are inorder[lo..hi].
function build(lo, hi) {
if (lo > hi) return null;
const value = preorder[next++]; // this subtree's root
const m = position.get(value);
const node = new TreeNode(value, null, null);
node.left = build(lo, m - 1); // left first: pre-order lists it first
node.right = build(m + 1, hi);
return node;
}
return build(0, inorder.length - 1);
}def rebuild_tree(preorder, inorder):
position = {v: i for i, v in enumerate(inorder)} # value -> index in inorder
next_index = 0 # next unused value in preorder
# Build the subtree whose values are inorder[lo..hi].
def build(lo, hi):
nonlocal next_index
if lo > hi:
return None
value = preorder[next_index] # this subtree's root
next_index += 1
m = position[value]
node = TreeNode(value)
node.left = build(lo, m - 1) # left first: pre-order lists it first
node.right = build(m + 1, hi)
return node
return build(0, len(inorder) - 1)Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.