-
Notifications
You must be signed in to change notification settings - Fork 0
/
098. Validate Binary Search Tree.cpp
74 lines (68 loc) · 2.07 KB
/
098. 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Solution 1. BF, O(n^2)
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(!root) return true;
if(!isValid(root->left, root->val, true) || !isValid(root->right, root->val, false)) return false;
return isValidBST(root->left) && isValidBST(root->right);
}
bool isValid(TreeNode* root, int bound, bool isLeft){
return !root || (isLeft ? root->val < bound : root->val > bound ) && isValid(root->left, bound, isLeft) && isValid(root->right, bound, isLeft);
}
};
// Solution 2. D & C, O(n)
class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValid(root, NULL, NULL);
}
bool isValid(TreeNode* root, TreeNode* minNode, TreeNode* maxNode){
if(!root) return true;
if(minNode && root->val <= minNode->val || maxNode && root->val >= maxNode->val) return false;
return isValid(root->left, minNode, root) && isValid(root->right, root, maxNode);
}
};
// Solution 3. In-order, recursive, O(n).
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* pre = NULL;
return isValid(root, pre);
}
bool isValid(TreeNode* root, TreeNode* &pre){
if(!root) return true;
if(!isValid(root->left, pre)) return false;
if(pre && root->val <= pre->val) return false;
pre = root;
return isValid(root->right, pre);
}
};
// Solution 4. In-order, iterative, O(n).
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*>s;
TreeNode* pre = NULL;
while(root || !s.empty()){
while(root){
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
if(pre && root->val <= pre->val) return false;
pre = root;
root = root->right;
}
return true;
}
};