Shared Boss in the ID Tree
Easy · Trees & BSTs · about 15 min
A company stores its staff in a binary search tree keyed by employee id: every id in a person's left subtree is smaller than theirs and every id in the right subtree is bigger. Ids are distinct. 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 ids a and b that are both in the tree, return the id of their lowest shared boss: the deepest person who has both of them in their subtree. A person counts as being in their own subtree, so if a is above b, the answer is a. a may equal b, and a may be bigger than b.
- Up to 10,000 people, ids are any distinct integers.
Examples:
bst_shared_manager([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], 2, 8) → 6
bst_shared_manager([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], 2, 4) → 2
Hints
- Compare both ids with the current person's id. What does the BST rule tell you about where they live?
- If they are on different sides, or one of them is the current person, you are done.
- Do not assume a is the smaller one.
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)
- Floor-by-Floor Roster (Medium)
- Unbeaten on the Way Down (Medium)
- Longest Handoff Chain (Medium)
- Shelf Index Check (Medium)
- K-th Cheapest Price (Medium)
- Closest Shared Folder (Medium)
- Rebuild the Bracket (Medium)
- Best Relay Route (Hard)
- Downhill Trails With a Target Sum (Hard)
- Office Wi-Fi Repeaters (Hard)