Rebuild a Category Tree From Preorder and Inorder Crawl Logs
Last updated: November 29, 2026
Quick Overview
A crawler logged the browse category tree of an Amazon marketplace twice: once in preorder and once in inorder, with unique category IDs. Reconstruct the binary tree from the two lists.
Amazon
November 29, 20260
0
0 solved
A crawler logged the browse category tree of an Amazon marketplace twice: once in preorder and once in inorder, with unique category IDs. Reconstruct the binary tree from the two lists.
This shows up in Amazon technical screens as a test of recursive decomposition, dressed up as restoring a catalog taxonomy after a cache loss. The interviewer looks for the index-map optimization and correct boundary arithmetic rather than slicing lists on every call.
What the Interviewer Expects
- Explain that preorder's first element is the root and its position in inorder splits left and right subtrees
- Use a value-to-index map for O(1) lookups
- Pass index bounds instead of slicing to stay O(n)
- State the uniqueness assumption and why duplicates break the problem
- Verify the result by re-traversing on a small example
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Can you rebuild the tree from postorder and inorder instead?
- Why can preorder and postorder alone not uniquely determine a binary tree?
- How would you make this iterative to avoid recursion depth limits?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Inputs: two lists of equal length n holding the same unique integers, a valid preorder and inorder traversal of some binary tree. Output: the root of that tree. If n is 0, return None....
High-Level Design
Preorder is root, left subtree, right subtree. Inorder is left subtree, root, right subtree. So the next unused preorder value is the root of the current range, and its inorder position m says that ...