Problem Description
Given the root of a binary tree, find the lowest common ancestor (LCA) of two given nodes, p and q. A node can be a descendant of itself. If either p or q does not exist in the tree, return null.
Key Insights
- Use a DFS (Depth-First Search) recursion to traverse the tree.
- For each node, check if it is equal to p or q.
- Recursively search the left and right subtrees.
- If both left and right recursive calls return non-null values, the current node is the LCA.
- To ensure both nodes exist in the tree, use flags (or count) when p or q are encountered during traversal.
- If after the DFS traversal one of the nodes was not found, return null.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes, since we traverse every node in the worst-case. Space Complexity: O(n) in the worst-case due to the recursion stack.
Solution
We perform a DFS recursion that checks each node to determine if it matches either p or q. While recursing, we record if p and q have been found using additional flags. At each node, if the left and right subtrees yield a non-null result, it means that the current node is the lowest common ancestor. After the DFS completes, we verify that both nodes were found. If either node is missing, we return null. This approach ensures that we get the true LCA only when both nodes exist in the tree.