力扣刷题-98. 验证二叉搜索树

题目

题解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int getMin(struct TreeNode* root){
    int min = root->val;
    if(root->left != NULL){
        min = getMin(root->left)<min? getMin(root->left):min;
    }
    //由于已经验证root是二叉搜索树,因此比较小值只可能存在左子树中
    // if(root->right != NULL){
    //     min = getMin(root->right)<min? getMin(root->right):min;
    // }
    return min;
}

int getMax(struct TreeNode* root){
    int max = root->val;
    //由于已经验证root是二叉搜索树,因此比较大值只可能存在右子树中
    // if(root->left != NULL){
    //     max = getMax(root->left)>max? getMax(root->left):max;
    // }
    if(root->right != NULL){
        max = getMax(root->right)>max? getMax(root->right):max;
    }
    return max;
}

bool isValidBST(struct TreeNode* root){
    if(root == NULL) return true;
    if(isValidBST(root->left)&&isValidBST(root->right)){
        int flag = 1;
        //不能小于等于左边的最大值。
        if(root->left != NULL){
            if(root->val <= getMax(root->left)){
                flag = 0;
            }
        }
        //不能大于等于右边的最小值。
        if(root->right != NULL){
            if(root->val >= getMin(root->right)){
                flag = 0;
            }
        }
        if(flag == 1){
            return true;
        }
    }
    return false;
}

要点

  1. 验证二叉搜索树不像验证二叉平衡树那样两边子树都是获取高度(详见力扣刷题-110.平衡二叉树)。

  1. 二叉搜索树是在确认两子树都是二叉搜索树的情况下,左边获取最大值,右边获取最小值,进行比较。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东东咚咚东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值