Given the preorder and inorder traversals of a binary tree with distinct values, construct and return the tree.
Before you code
Preorder starts with the root. In inorder, everything left of the root belongs to the left subtree and everything right of it to the right subtree. That splits both lists, and each part is the same problem again.
Hints
- Build a map from value to inorder index, so finding the root's position is O(1).
- Recurse with index ranges instead of slicing lists, to stay O(n).
- Consume preorder from the front with a single moving index: build the left subtree before the right, because preorder lists it first.
Production & complexity notes
When solving Construct binary tree from preorder and inorder traversal on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Vocabulary and traversals to reinforce the underlying pattern.
What it practices
What each traversal order reveals about a tree's shape, from Vocabulary and traversals.