Skip to content

Commit 16c2ee3

Browse files
Merge pull request #140 from aryanandarnav13/patch-5
Create lowest_common_ancestor.cpp
2 parents e80b020 + 8b2f935 commit 16c2ee3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

lowest_common_ancestor.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <iostream>
2+
3+
struct TreeNode {
4+
int val;
5+
TreeNode* left;
6+
TreeNode* right;
7+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
8+
};
9+
10+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
11+
if (!root) return nullptr;
12+
13+
if (p->val < root->val && q->val < root->val) {
14+
return lowestCommonAncestor(root->left, p, q);
15+
} else if (p->val > root->val && q->val > root->val) {
16+
return lowestCommonAncestor(root->right, p, q);
17+
} else {
18+
return root;
19+
}
20+
}
21+
22+
int main() {
23+
// Create a BST
24+
TreeNode* root = new TreeNode(20);
25+
root->left = new TreeNode(10);
26+
root->right = new TreeNode(30);
27+
root->left->left = new TreeNode(5);
28+
root->left->right = new TreeNode(15);
29+
root->right->left = new TreeNode(25);
30+
root->right->right = new TreeNode(35);
31+
32+
TreeNode* p = root->left->left; // Node with value 5
33+
TreeNode* q = root->left->right; // Node with value 15
34+
35+
TreeNode* lca = lowestCommonAncestor(root, p, q);
36+
37+
if (lca) {
38+
std::cout << "Lowest Common Ancestor: " << lca->val << std::endl;
39+
} else {
40+
std::cout << "No common ancestor found." << std::endl;
41+
}
42+
43+
// Clean up memory (not shown for brevity)
44+
return 0;
45+
}

0 commit comments

Comments
 (0)