Question presented to candidate: "I give you two arrays: the preorder and the inorder traversal of a binary tree whose values are all distinct. Write a Python function that rebuilds the tree and returns its root."
What a strong answer should cover:
- Preorder's first value is the root; finding that value in inorder splits the remaining values into the left subtree (before it) and the right subtree (after it).
- Recurse on the two parts; the left subtree's preorder comes first, so build left before right while consuming preorder with one moving index.
- A value โ index hash map makes each split O(1), giving O(n) total; a linear search per node is O(nยฒ) on a skewed tree.
- Pass index ranges instead of copying sub-arrays.
- Why the values must be distinct (duplicates make the answer ambiguous) and why preorder + postorder alone is not enough in general.
- Python specifics: a dict comprehension for the index map,
nonlocalfor the shared preorder index, and whyinorder.index(...)plus slicing (preorder[1:mid + 1]) quietly makes it O(nยฒ).
Clarifying questions expected:
- Are all values distinct, and are the two arrays guaranteed to describe the same tree?
- How large can n be (is recursion depth a concern)?
Code / implementation expected: Yes โ a recursive helper over inorder index ranges with a dict for positions, in Python 3.