Problem 159
Lowest Common Ancestor of a Binary Tree
Medium · 20 pts · Tree, Depth-First Search, Binary Tree
Problem
You are given a binary tree with distinct values (not necessarily a search tree) and two values P and Q that are both in it. Print the value of their lowest common ancestor: the deepest node that has both P and Q in its subtree. A node counts as being in its own subtree, so if P is an ancestor of Q, the answer is P. A recursive search works: return the node if it is P or Q; otherwise search both subtrees. If both sides find something, the current node is the answer; if only one side does, pass that result up.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses). Third line: the values P and Q.
Output
Print the value of the lowest common ancestor.
Constraints
2 <= number of nodes <= 100000; values are distinct; P != Q, both present
Example input
11 3 5 1 6 2 0 8 null null 7 4 5 1
Example output
3
Explanation
The value 5 is the root's left child and 1 is the root's right child. They are in different subtrees of the root 3, so the lowest common ancestor is 3.