-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidateBinarySearchTree.cpp
More file actions
51 lines (47 loc) · 1.21 KB
/
ValidateBinarySearchTree.cpp
File metadata and controls
51 lines (47 loc) · 1.21 KB
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
/**
* 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:
bool isValidBST(TreeNode* root) {
return valid(root, NULL, NULL);
}
bool valid(TreeNode* root, TreeNode* minnode, TreeNode* maxnode)
{
if (root == NULL) return true;
if ((minnode && root->val <= minnode->val) || (maxnode && root->val >= maxnode->val))
return false;
return valid(root->left, minnode, root) && valid(root->right, root, maxnode);
}
};
// 第二种解法:迭代
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*> stk;
if (!root) return true;
TreeNode* pre = NULL;
while (root || !stk.empty())
{
while (root)
{
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
if (pre && pre->val >= root->val)
return false;
pre = root;
root = root->right;
}
return true;
}
};