LeetCode 236 - Lowest Common Ancestor of a Binary Tree
Table of Contents
Problem Statement
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).β
Using Tree DFS
Explanation
We use Tree DFS to efficiently traverse a tree.
Base Case:
If the current node is
nullptr, that means weβve reached the end of a branch.If the current node matches
porq, weβve found one of the nodes.
Recursive Search:
- Traverse both left and right subtrees to search for
pandq.
- Traverse both left and right subtrees to search for
Combine Results:
If one node is found in the left subtree and the other in the right subtree, the current node is their LCA.
If both are in the same subtree, propagate the result up the tree.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) {
return root;
}
return left ? left : right;
}
};
Conclusion
Time Complexity: π(π) - Where π is the number of nodes in the binary tree.
Space Complexity: π(β) - Where β is the height of the binary tree, due to the recursion stack.