forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
46 lines (35 loc) · 992 Bytes
/
main2.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
/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
/// Author : liuyubobobo
/// Time : 2018-12-16
#include <iostream>
#include <cassert>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Non-Recursive
/// Time Complexity: O(lgn), where n is the node's number of the tree
/// Space Complexity: O(1)
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return root;
TreeNode* cur = root;
while(cur) {
if (p->val < cur->val && q->val < cur->val)
cur = cur->left;
else if (p->val > cur->val && q->val > cur->val)
cur = cur->right;
else
return cur;
}
return NULL;
}
};
int main() {
return 0;
}