Photo by MakeSumo on Unsplash

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).”

APPROACH:

1. Base Case:
— If the current node (`root`) is `NULL` or one of the nodes `p` or `q`, return the current node. This is because the LCA is found, or one of the nodes is the ancestor of the other.

2. Recursive Calls:
— Recursively call the `lowestCommonAncestor` function on the left and right subtrees.

3. Check for LCA:
— Check the results of the recursive calls (`left` and `right`).
— If one of the results is `NULL`, it means the LCA is in the other subtree, so return the non-NULL result.
— If both results are non-NULL, it means the current node is the LCA, so return the current node.

CODE:

#include <bits/stdc++.h>
using namespace std;

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 == NULL || p == root || q == root) {
return root;
}
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);

if (left == NULL) {
return right;
} else if (right == NULL) {
return left;
} else {
return root; // answer
}
}
};

int main() {
// Create a sample binary tree
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(5);
root->right = new TreeNode(1);
root->left->left = new TreeNode(6);
root->left->right = new TreeNode(2);
root->right->left = new TreeNode(0);
root->right->right = new TreeNode(8);
root->left->right->left = new TreeNode(7);
root->left->right->right = new TreeNode(4);

Solution solution;

// Test cases
TreeNode* p = root->left;
TreeNode* q = root->right;
TreeNode* result = solution.lowestCommonAncestor(root, p, q);
cout << "Lowest Common Ancestor of " << p->val << " and " << q->val << " is: " << result->val << endl;

return 0;
}

--

--

Sheefa Naaz

Passionate about Data Structures and Algorithms | Programming