-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathLowestCommonAncestorInBinarySearchTree.cpp
More file actions
51 lines (33 loc) · 1.05 KB
/
LowestCommonAncestorInBinarySearchTree.cpp
File metadata and controls
51 lines (33 loc) · 1.05 KB
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
// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
/**
* 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) {
while(root!=NULL) {
if(root->val<p->val && root->val<q->val)
root= root->right;
else if (root->val>p->val && root->val>q->val)
root= root->left;
else
break;
}
return root;
// Recursive Approach
// if(root==NULL)
// return NULL;
// if(root->val<p->val && root->val<q->val)
// return lowestCommonAncestor(root->right, p, q);
// else if (root->val>p->val && root->val>q->val)
// return lowestCommonAncestor(root->left, p, q);
// else
// return root;
}
};