/**
* 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 helper(root, LONG_MIN, LONG_MAX);
}
private:
bool helper(const TreeNode* root, long min, long max) {
if (root == nullptr) return true;
if (root->val >= max || root->val <= min) return false;
return helper(root->left, min, root->val) && helper(root->right, root->val, max);
}
};
// 循环
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (root == nullptr) return true;
auto ranges = queue<pair<long, long>>();
ranges.push(make_pair(LONG_MIN, LONG_MAX));
auto nodes = queue<const TreeNode*>();
nodes.push(root);
while (!nodes.empty()) {
auto sz = nodes.size();
for (auto i = 0; i < sz; ++i) {
auto range = ranges.front();
ranges.pop();
auto n = nodes.front();
nodes.pop();
if (n->val >= range.second || n->val <= range.first) {
return false;
}
if (n->left != nullptr) {
ranges.push(make_pair(range.first, n->val));
nodes.push(n->left);
}
if (n->right != nullptr) {
ranges.push(make_pair(n->val, range.second));
nodes.push(n->right);
}
}
}
return true;
}
};