[Geeks for Geeks] Lowest Common Ancestor in a Binary Tree

Lowest Common Ancestor in a Binary Tree

Given a Binary Tree with all unique values and two nodes value, n1 and n2. The task is to find the lowest common ancestor of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them are present.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
pair<bool, Node*> helper(Node* root, int n1, int n2) {
if(!root) return {false, NULL};
if(root->data == n1 or root->data == n2) {
auto l = helper(root->left, n1, n2);
if(l.first) return {true, root};
auto r = helper(root->right, n1, n2);
if(r.first) return {true, root};
return {true, NULL};
}
auto l = helper(root->left, n1, n2);
if(l.first and l.second) return l;
auto r = helper(root->right, n1, n2);
if(r.first and r.second) return r;
if(l.first and r.first) return {true, root};
return {l.first or r.first, NULL};
}
//Function to return the lowest common ancestor in a Binary Tree.
Node *lca(Node *root, int n1, int n2) {
return helper(root, n1, n2).second;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/lowest-common-ancestor-in-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.