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. The owner kept the layout as a binary tree in a file, and the file is now corrupted. Two printouts survived.

The first printout lists the cards in "card first, then everything on its left, then everything on its right" order. The second lists them in "everything on the left, then the card, then everything on the right" order. The owner wants the tree back exactly as it was.

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

The pre-order list starts with 4, so 4 is the first card. In the in-order list, 7 and 2 come before 4 (its left side) and 6 and 1 come after (its right side). Repeat on each side: on the left, pre-order says 7 comes 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

The direct recursion takes the root from the front of pre-order, scans the in-order list to find it, then slices both lists into new left and right lists and recurses on the copies.

The idea is right, but every level scans and copies lists. For a tree that is one long chain of 1,000 cards, each step copies almost the whole list again: about 1,000 + 999 + … + 1 ≈ 500,000 element copies, which is O(n²). A hash map of positions removes the scans, and working with index ranges instead of slices removes 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