验证搜索二叉树
一开始写法没考虑到以下情况,以为只要当前左节点小于根结点就可以,导致写下错误的代码。
[5,4,6,null,null,3,7]
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == nullptr) return true;
bool valid1 = isValidBST(root->left);
bool valid2 = isValidBST(root->right);
if(valid1 && valid2){
if(root->left) {
if(root->val <= root->left->val){
return false;
}
}
if(root->right){
if(root->val >= root->right->val){
return false;
}
}
return true;
}
return false;
}
};
正确解法如下:
1.定义辅助函数: 这个函数意思为以root为根节点的子树,判断值是否都在(l,r)之间。
bool helper(TreeNode* root, int l , int r){
}
class Solution {
public:
bool helper(TreeNode* root, long long l , long long r){
if(root == nullptr) return true;
if(root->val <= l || root->val >= r ) return false;
return helper(root->left,l , root->val) && helper(root->right,root->val,r);
}
bool isValidBST(TreeNode* root) {
return helper(root,LONG_MIN,LONG_MAX);
}
};