-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0098-validate-binary-search-tree.cpp
102 lines (90 loc) · 2.53 KB
/
0098-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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
Given root of binary tree, determine if it's valid (left all < curr, right all > curr)
Inorder traversal & check if prev >= curr, recursive/iterative solutions
Time: O(n)
Space: O(n)
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
return helper(root, LONG_MIN, LONG_MAX);
}
private:
bool helper(TreeNode* root, long left, long right){
if (!root)
return true;
if (root->val < right && root->val > left){
return helper(root->left, left, root->val) && helper(root->right, root->val, right);
}
return false;
}
};
/*
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* prev = NULL;
return inorder(root, prev);
}
private:
bool inorder(TreeNode* root, TreeNode*& prev) {
if (root == NULL) {
return true;
}
if (!inorder(root->left, prev)) {
return false;
}
if (prev != NULL && prev->val >= root->val) {
return false;
}
prev = root;
if (!inorder(root->right, prev)) {
return false;
}
return true;
}
};
*/
// class Solution {
// public:
// bool isValidBST(TreeNode* root) {
// stack<TreeNode*> stk;
// TreeNode* prev = NULL;
// while (!stk.empty() || root != NULL) {
// while (root != NULL) {
// stk.push(root);
// root = root->left;
// }
// root = stk.top();
// stk.pop();
// if (prev != NULL && prev->val >= root->val) {
// return false;
// }
// prev = root;
// root = root->right;
// }
// return true;
// }
// };