Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Input: root = [1,2], p = 1, q = 2
Output: 1
Node.val are unique.p != qp and q will exist in the tree.This approach involves recursively traversing the binary tree from the root node and returning the lowest common ancestor. The idea is to essentially perform a post-order traversal of the tree while returning conditions that help conclude the LCA.
p or q, we return this node as a candidate for the LCA.p and q.p and q are found in different subtrees of the current node, making the current node the LCA.In this approach, we utilize a parent pointer for all nodes starting from the root. Once we have parent pointers, we can track the path from each node p and q to the root. The first common node in these two paths is the LCA.
p to the root and save all visited ancestors in a set.q and find the first common ancestor in the set.This approach is a refined version of the first recursive approach. It involves a single recursive post-order traversal to find the LCA more clearly and concisely.
null, return null, indicating that neither p nor q is found below.p or q, return the current node.