1643. Common Root of Many
A company chart is stored as a binary tree whose node values are distinct employee ids. A committee is formed from the ids listed in vals, and every listed id is guaranteed to appear in the chart. Find the lowest manager who is above every committee member: the deepest node whose subtree contains all of them. A node counts as part of its own subtree, so when one member sits above all the others, that member is the answer.
Return that actual node of the input tree, not a copy; the judge reports it by its position. The ids in vals are distinct and appear in no particular order. Solve it with one pass that counts, for each subtree, how many committee members it holds, in O(n) time and O(n) extra space.
Example 1
- Input:
- root = [10,4,15,2,7,12,20,null,3,null,9], vals = [3,9]
- Output:
- 1
- Explanation:
Value 3 hangs below node 2 and value 9 below node 7, and both of those nodes are children of node 4, so node 4 is the lowest node above both.
Example 2
- Input:
- root = [10,4,15,2,7,12,20,null,3,null,9], vals = [7,9]
- Output:
- 4
- Explanation:
Node 9 is inside the subtree of node 7, so node 7 covers both members and is its own ancestor; it is returned.
Constraints
1 ≤ nodes ≤ 1000; 1 ≤ vals.length ≤ nodes; all node values are distinct integers in [-109, 109]; vals holds distinct values that all exist in the tree
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)