Mental Model
Find the shared parent node where two nodes meet first when moving up the tree.
Analogy: Like finding the closest common boss for two employees in a company hierarchy tree.
1
/ \
2 3
/ \ \
4 5 6
1
/ \
2 3
/ \ \
4 5 6
At node 1: searching left subtree -> 2, right subtree -> 3
At node 2: left child -> 4, right child -> 5
Found node 4 at left child of 2
Found node 5 at right child of 2
LCA found at node 2
2 is the lowest common ancestor of nodes 4 and 5
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr) return nullptr; // base case: empty subtree if (root == p || root == q) return root; // found one target node TreeNode* left = lowestCommonAncestor(root->left, p, q); // search left subtree TreeNode* right = lowestCommonAncestor(root->right, p, q); // search right subtree if (left != nullptr && right != nullptr) return root; // both nodes found in different subtrees if (left != nullptr) return left; // both nodes in left subtree return right; // both nodes in right subtree or none found } int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); root->right->right = new TreeNode(6); TreeNode* p = root->left->left; // node 4 TreeNode* q = root->left->right; // node 5 TreeNode* lca = lowestCommonAncestor(root, p, q); if (lca != nullptr) { cout << lca->val << "\n"; } else { cout << "No common ancestor found\n"; } return 0; }
if (root == nullptr) return nullptr;if (root == p || root == q) return root;TreeNode* left = lowestCommonAncestor(root->left, p, q);TreeNode* right = lowestCommonAncestor(root->right, p, q);if (left != nullptr && right != nullptr) return root;if (left != nullptr) return left;return right;if (root == nullptr) return nullptr;
if (root == p || root == q) return root;
if (root == p || root == q) return root;