Lowest Common Ancestor of a Binary Tree
You are given the root of a binary tree. This tree is not necessarily a search tree. The lowest common ancestor of the values p and q is the deepest node that has both of them in its subtree (a node counts as being in its own subtree). Return the value of that node. All values in the tree are distinct, and p and q are two different values that are in the tree.
Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.
Example 1
root [3,5,1,6,2,0,8,null,null,7,4]
p 5
q 1
returns 3
They meet at the root, 3.
Example 2
root [3,5,1,6,2,0,8,null,null,7,4]
p 5
q 4
returns 5
4 is below 5, so the answer is 5.
Constraints
2 <= number of nodes <= 100- Values in the tree are distinct.
p != q, and both are values in the tree.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.