forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate-binary-search-tree.cpp
78 lines (68 loc) · 1.71 KB
/
validate-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
72
73
74
75
76
77
78
// Time: O(n)
// Space: O(1)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Morris Traversal
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode *prev = nullptr;
TreeNode *curr = root;
while (curr) {
if (!curr->left) {
if (prev && prev->val >= curr->val) {
return false;
}
prev = curr;
curr = curr->right;
} else {
TreeNode *node = curr->left;
while (node->right && node->right != curr) {
node = node->right;
}
if (!node->right) {
node->right = curr;
curr = curr->left;
} else {
if (prev && prev->val >= curr->val) {
return false;
}
prev = curr;
node->right = nullptr;
curr = curr->right;
}
}
}
return true;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
bool isValidBST(TreeNode* root) {
if (!root) {
return true;
}
if (!isValidBST(root->left)) {
return false;
}
if (last && last != root && last->val >= root->val) {
return false;
}
last = root;
if (!isValidBST(root->right)) {
return false;
}
return true;
}
private:
TreeNode *last = nullptr;
};