Closest Shared Folder
Medium · Trees & BSTs · about 20 min
A shared drive is a binary tree of folders with distinct ids (not sorted in any way). The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.
Given two folder ids a and b that are both in the tree, return the id of their closest shared folder: the deepest folder that contains both of them. A folder counts as containing itself, so if a is inside b, the answer is b. a may equal b.
- Up to 10,000 folders, ids are any distinct integers.
Examples:
closest_shared_folder([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 1) → 3
closest_shared_folder([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 4) → 5
Hints
- Let each call report back whether its subtree contains a or b.
- When both the left side and the right side report a find, what does that say about the current folder?
- If the current folder is a or b itself, you can stop going down.
Learn the pattern first: the Trees & BSTs lesson.
More Trees & BSTs problems
- Levels in the Org Chart (Easy)
- Mirror the Folder Tree (Easy)
- Twin Backup Check (Easy)
- Exact Budget Trail (Easy)
- Shared Boss in the ID Tree (Easy)
- Floor-by-Floor Roster (Medium)
- Unbeaten on the Way Down (Medium)
- Longest Handoff Chain (Medium)
- Shelf Index Check (Medium)
- K-th Cheapest Price (Medium)
- Rebuild the Bracket (Medium)
- Best Relay Route (Hard)
- Downhill Trails With a Target Sum (Hard)
- Office Wi-Fi Repeaters (Hard)