Lowest Common Ancestor of a BST
You are given the root of a binary tree. The lowest common ancestor of two 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. Both p and q are in the tree and are different. In a binary search tree every value in a left subtree is smaller than its node and every value in a right subtree is larger.
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
2 and 8 split at the root, 6.
Example 2
4 is below 2, so the answer is 2.
Constraints
2 <= number of nodes <= 100- The tree is a valid BST with distinct values.
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.