Problem Description
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. The lowest common ancestor is defined as the lowest node in the tree that has both nodes as descendants (where a node can be a descendant of itself).
Key Insights
- The LCA is the deepest node that is an ancestor to both given nodes.
- We can traverse the tree using Depth-First Search (DFS) to find the LCA.
- If either of the nodes is found during traversal, we can return that node as a potential ancestor.
- The search continues until both nodes are found, ensuring the lowest common ancestor is identified.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes in the tree, as we may need to traverse all nodes in the worst case. Space Complexity: O(H), where H is the height of the tree, due to the recursive stack space used in DFS.
Solution
We will use a Depth-First Search (DFS) approach to traverse the binary tree. Starting from the root, we will check if the current node is either of the nodes we are looking for. If we find one of the nodes, we return that node. During the traversal, if we find both nodes among the left and right subtrees of a node, then that node is the lowest common ancestor.