Skip to content

Commit 60b8388

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <[email protected]>
1 parent e838cd2 commit 60b8388

File tree

4 files changed

+58
-2
lines changed

4 files changed

+58
-2
lines changed

0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ struct TreeNode {
88
struct TreeNode *right;
99
};
1010

11-
static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q)
11+
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q)
1212
{
1313
if (root == NULL || root->val == p->val || root->val == q->val) {
1414
return root;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* struct TreeNode {
8+
* int val;
9+
* TreeNode *left;
10+
* TreeNode *right;
11+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
12+
* };
13+
*/
14+
15+
class Solution {
16+
public:
17+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
18+
if (root == nullptr || root->val == p->val || root->val == q->val) {
19+
return root;
20+
} else if (root->val < p->val && root->val < q->val) {
21+
return lowestCommonAncestor(root->right, p, q);
22+
} else if (root->val > p->val && root->val > q->val) {
23+
return lowestCommonAncestor(root->left, p, q);
24+
} else {
25+
return root;
26+
}
27+
}
28+
};

0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ struct TreeNode {
99
struct TreeNode *right;
1010
};
1111

12-
static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q)
12+
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q)
1313
{
1414
if (root == NULL || root == p || root == q) {
1515
/* edge cases: if return NULL then no p or q node in this path */
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
16+
if (root == nullptr || root == p || root == q) {
17+
return root;
18+
}
19+
20+
TreeNode *l = lowestCommonAncestor(root->left, p, q);
21+
TreeNode *r = lowestCommonAncestor(root->right, p, q);
22+
if (l != nullptr && r != nullptr) {
23+
return root;
24+
} else {
25+
return l != nullptr ? l : r;
26+
}
27+
}
28+
};

0 commit comments

Comments
 (0)