forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0235-lowest-common-ancestor-of-a-binary-search-tree.cpp
47 lines (42 loc) · 1.26 KB
/
0235-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
/*
Given a binary search tree (BST), find the LCA of 2 given nodes in the BST
Use BST property: if curr > left & right go left, else if < go right, else done
Time: O(n)
Space: O(n)
*/
/**
* 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 (p->val < root->val && q->val < root->val) {
return lowestCommonAncestor(root->left, p, q);
} else if (p->val > root->val && q->val > root->val) {
return lowestCommonAncestor(root->right, p, q);
} else {
return root;
}
}
};
// class Solution {
// public:
// TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// while (root != NULL) {
// if (p->val < root->val && q->val < root->val) {
// root = root->left;
// } else if (p->val > root->val && q->val > root->val) {
// root = root->right;
// } else {
// return root;
// }
// }
// return NULL;
// }
// };