Closest shared ancestor
Write shared_ancestor(root, p, q): given the root of a binary tree and two different nodes p and q that are both in it, return the deepest node whose subtree contains both of them. A node belongs to its own subtree, so if p sits above q, the answer is p. It is not a search tree: the values are distinct but in no particular order. Each TreeNode has val, left and right.
The tests call the provided run_shared_ancestor(values, p, q), where values lists the tree level by level with null for a missing child ([1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3), p and q are the values of the two nodes, and the result is the value of the node you return.
Aim for one pass over the tree.
Besides the tests, one large input (a 10,387-node tree, 653 levels tall) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.
Examples
run_shared_ancestor([3,5,1,6,2,0,8,null,null,7,4], 6, 4)→5run_shared_ancestor([3,5,1,6,2,0,8,null,null,7,4], 5, 4)→5run_shared_ancestor([3,5,1,6,2,0,8,null,null,7,4], 7, 8)→3