Leetcode 236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
Here are a few clarifying questions to ensure we understand the requirements correctly:
p
and q
are distinct nodes in the given tree.p
and q
are found in different branches, hence the current node is the LCA.p
and q
are in one subtree, or one is found (we return the non-null result up).p
or q
, it is an ancestor.nullptr
, return nullptr
.p
or q
, return the current node./**
* 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) {
// Base case: if the current node is NULL, return NULL
if (root == nullptr) {
return nullptr;
}
// If either p or q is the current node, we return the current node
if (root == p || root == q) {
return root;
}
// Recur for the left and right subtree
TreeNode* leftLCA = lowestCommonAncestor(root->left, p, q);
TreeNode* rightLCA = lowestCommonAncestor(root->right, p, q);
// If both the left and right contributions are non-null
if (leftLCA != nullptr && rightLCA != nullptr) {
return root;
}
// Otherwise check if left subtree or right subtree is the LCA
return (leftLCA != nullptr) ? leftLCA : rightLCA;
}
};
This code recursively explores the tree to find the lowest common ancestor by leveraging the depth-first search approach. Each node is evaluated in terms of whether it is the root of the subtree containing both p
and q
, and the decision is made on that basis.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?