要求:rt
思路:
法一:递归,右子树范围在(根,inf),左子树范围在(-inf,根),注意下一个递归就不是inf了,比如5右儿子8,8左儿子7,应该验证7范围在(5,8)
/**
* 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 check(TreeNode* root,long left,long right){
if(!root)return true;
if(root->val<=left||root->val>=right)return false;
return check(root->left,left,root->val)&&check(root->right,root->val,right);
}
bool isValidBST(TreeNode* root) {
return check(root,LONG_MIN,LONG_MAX);
}
};
法二:中序遍历
/**
* 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:
long long pre=LONG_MIN;
bool inorder(TreeNode* root){
if(!root)return true;
if(!inorder(root->left))return false;;
if(root->val<=pre)return false;
pre=root->val;
return inorder(root->right);
}
bool isValidBST(TreeNode* root) {
return inorder(root);
}
};