You are given a binary tree and two distinct nodes, p and q.
Your task is to find the lowest common ancestor (LCA) of nodes p and q. The LCA is defined as the lowest node in the tree that has both p and q as descendants.
You may assume that:
p and q will always exist in the given tree.p and q will always be distinct from each other.Return the LCA node.
p = 2
q = 3
1
The LCA of nodes with values 2 and 3 is the node with value 1, which is their parent.
p = 1
q = 2
1
The LCA of nodes with values 1 and 2 is the node with value 1, since a node can be a descendant of itself.
p = 8
q = 5
2
The LCA of nodes with values 8 and 5 is the node with value 2, which is their lowest common ancestor.
p = 2
q = 3
1