File tree 4 files changed +58
-2
lines changed
0235_lowest_common_ancestor_of_a_binary_search_tree
0236_lowest_common_ancestor_of_a_binary_tree
4 files changed +58
-2
lines changed Original file line number Diff line number Diff line change @@ -8,7 +8,7 @@ struct TreeNode {
8
8
struct TreeNode * right ;
9
9
};
10
10
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 )
12
12
{
13
13
if (root == NULL || root -> val == p -> val || root -> val == q -> val ) {
14
14
return root ;
Original file line number Diff line number Diff line change
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
+ };
Original file line number Diff line number Diff line change @@ -9,7 +9,7 @@ struct TreeNode {
9
9
struct TreeNode * right ;
10
10
};
11
11
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 )
13
13
{
14
14
if (root == NULL || root == p || root == q ) {
15
15
/* edge cases: if return NULL then no p or q node in this path */
Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments