-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path235 Lowest Common Ancestor of a Binary Search Tree.cpp
71 lines (62 loc) · 1.98 KB
/
235 Lowest Common Ancestor of a Binary Search Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// refer to discussion in LeetCode
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if ( !root )
return NULL;
if ( root == p || root == q )
return root;
TreeNode* l = lowestCommonAncestor( root->left, p, q);
TreeNode* r = lowestCommonAncestor( root->right, p, q);
if ( l && r )
return root;
else if ( !l )
return r;
else
return l;
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode *lca = root;
while (lca) {
if (lca == p || lca == q || (lca->val > min(p->val, q->val) && lca->val < max(p->val, q->val)) )
break;
else if (lca->val < min(p->val, q->val))
lca = lca->right;
else if (lca->val > max(p->val, q->val))
lca = lca->left;
}
return lca;
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root){
return NULL;
}
// check if the current value is larger than both nodes , go left
if(p->val < root->val && q->val < root->val){
lowestCommonAncestor(root->left , p , q);
// go right
}else if(p->val > root->val && q->val > root->val){
lowestCommonAncestor(root->right , p , q);
}// my LCA
else{
return root;
}
}
};