File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments