Given a binary tree and two node values p and q, return the value of their lowest common ancestor (LCA): the deepest node that has both p and q as descendants (a node can be a descendant of itself).
[2, 10⁴].-10⁹ ≤ Node.val ≤ 10⁹Node.val are unique.p ≠ qp and q will exist in the tree.Recurse left and right; if both return non-null, the current node is the LCA.
Every node in the tree has exactly one way down to it from the root. The ancestors of a node are the nodes on that way down, the node itself included. So the common ancestors of p and q are the nodes the two ways down share, and the lowest one is the last node they share before they go separate ways.
Time O(n)Space O(h)
The full walkthrough and code are part of Premium
3