Problem 607
Lowest Common Ancestor of Deepest Leaves
Medium · 20 pts · Tree, Depth-First Search
Problem
The deepest leaves of a binary tree are the nodes at the greatest depth. Find their lowest common ancestor: the deepest node whose subtree contains all of them. If there is only one deepest leaf, the answer is that leaf itself. All values are distinct, so print the value of the answer node. A post-order search can return, for each subtree, its height together with the LCA of its deepest leaves.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. All values are distinct.
Output
Print the value of the lowest common ancestor of the deepest leaves.
Constraints
1 <= number of nodes <= 1000; 0 <= value <= 1000; values are distinct
Example input
11 3 5 1 6 2 0 8 null null 7 4
Example output
2
Explanation
In the tree 3 5 1 6 2 0 8 null null 7 4, the deepest leaves are 7 and 4, both children of the node 2. So their lowest common ancestor is 2.