codejump
MediumPro challengePythonJavaScriptTypeScript

Binary Tree — Rebuild from Preorder and Inorder

Data StructuresTreesRecursionHash Table

solve(preorder, inorder) — two traversals of the same binary tree with
unique values are given. Rebuild the tree and return it serialized level by level
with the provided toLevelOrder helper.

  • Preorder visits *node, left, right* — its first element is the root.
  • Inorder visits *left, node, right* — the root splits it into the left and

right subtrees.

Examples

solve([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])  → [3, 9, 20, null, null, 15, 7]
solve([1, 2], [2, 1])                        → [1, 2]
solve([1, 2], [1, 2])                        → [1, null, 2]
solve([], [])                                → []

A map from value to its inorder index makes each lookup O(1), so the whole
rebuild is O(n) instead of O(n²).

Sample tests

Test #1Classic example
Input: [[3,9,20,15,7],[9,3,15,20,7]]
Output: [3,9,20,null,null,15,7]
Test #2Left child only
Input: [[1,2],[2,1]]
Output: [1,2]
Test #3Empty tree
Input: [[],[]]
Output: []