Rebuild the Escape Room Clues

MediumrecursionAlso known as Construct Binary Tree from Preorder and Inorder Traversal

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

Example 1
Input
preorder = [4, 7, 2, 1, 6]
inorder = [7, 2, 4, 6, 1]
Output
[4, 7, 1, null, 2, 6]
Why

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.

Example 2
Input
preorder = [1, 2]
inorder = [1, 2]
Output
[1, null, 2]
Why

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

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.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code