Discover how a simple recursive trick can save hours of confusing ancestor hunting!
Why Lowest Common Ancestor in Binary Tree in DSA C++?
Imagine you have a family tree on paper and you want to find the closest common grandparent of two cousins. You try to trace each cousin's ancestors manually, comparing each step. It quickly becomes confusing and slow as the tree grows.
Manually checking each ancestor for two nodes means retracing many paths repeatedly. It is easy to make mistakes, miss a common ancestor, or waste time going up and down the tree multiple times.
The Lowest Common Ancestor (LCA) method lets you find the closest shared ancestor of two nodes in a binary tree efficiently. It uses a simple recursive approach to explore the tree once and find the answer without repeated work.
bool isAncestor(Node* root, Node* target) {
if (!root) return false;
if (root == target) return true;
return isAncestor(root->left, target) || isAncestor(root->right, target);
}
Node* findLCA(Node* root, Node* node1, Node* node2) {
if (!root) return nullptr;
if (root == node1 || root == node2) return root;
if (isAncestor(root->left, node1) && isAncestor(root->left, node2))
return findLCA(root->left, node1, node2);
if (isAncestor(root->right, node1) && isAncestor(root->right, node2))
return findLCA(root->right, node1, node2);
return root;
}Node* findLCA(Node* root, Node* node1, Node* node2) {
if (!root) return nullptr;
if (root == node1 || root == node2) return root;
Node* leftLCA = findLCA(root->left, node1, node2);
Node* rightLCA = findLCA(root->right, node1, node2);
if (leftLCA && rightLCA) return root;
return leftLCA ? leftLCA : rightLCA;
}This concept enables quick and reliable discovery of the closest shared ancestor in any binary tree, unlocking efficient tree analysis and queries.
In a company's organizational chart, finding the lowest common manager of two employees helps understand reporting lines and collaboration paths.
Manual ancestor checks are slow and error-prone.
LCA uses recursion to find the closest shared ancestor efficiently.
It simplifies complex tree queries in many real-world scenarios.