验证的方法并不是每个节点都大于左边的,小于右边的,而是每个节点必须大于左子树每一个节点,小于右子树每一个节点。
方法一是给每个节点赋予一个上限和一个下限,每次判断节点值是否在界内。
方法二是看了一篇题解,根据二叉搜索树中序遍历后就是递增数列的原理进行。这个递归用的很妙
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
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 check(root, LLONG_MIN, LLONG_MAX);
}
bool check(TreeNode* root, long long lower, long long upper) {
if (root == nullptr) {
return true;
}
if (root->val <= lower || root->val >= upper)return false;
return check(root->left, lower, root->val) && check(root->right, root->val, upper);
}
};
class Solution1 {
long pre = LONG_MIN;
bool isValidBST(TreeNode* root) {
if (root == nullptr) {
return true;
}
if (!isValidBST(root->left)) {
return false;
}
if (root->val <= pre) {
return false;
}
pre = root->val;
return isValidBST(root->right);
}
};
void print(TreeNode* a) {
if (a != nullptr) {
cout << a->val;
print(a->left);
print(a->right);
}
}
int main() {
Solution test;
TreeNode* c = new TreeNode(1);
TreeNode* b = new TreeNode(3);
TreeNode* a = new TreeNode(2,c, b);
cout<<test.isValidBST(a);
}