I give you two arrays — the preorder traversal and the inorder traversal of a binary tree. Reconstruct the tree.
Preorder visits root-left-right. Inorder visits left-root-right. Two different visit orders of the same tree. But how do you use them to reconstruct the original structure?
Given just two flat arrays and a tree to reconstruct, the challenge is figuring out which elements belong where. The partition arithmetic that couples the two arrays is off-by-one-prone, and even deciding how many nodes go left vs right is trickier than it looks.
Start with the preorder. In preorder traversal the root is always visited first. Tap the root in the preorder array.