94. Lowest Common Ancestor in a Binary Tree
MediumTrees
Given a binary tree with distinct values and two values p and q that both appear in it, return the value of their lowest common ancestor: the deepest node that has both as descendants. A node counts as a descendant of itself.
The tree is not necessarily a search tree.
A binary tree is passed as TreeNode objects with val, left and right. The tests write trees in level order, with null for a missing child.
Example 1
Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 4 Output: 5
Constraints
2 ≤ nodes ≤ 10⁵p ≠ q, and both exist in the tree