验证二叉搜索树

验证二叉搜索树
 https://leetcode.cn/problems/validate-binary-search-tree/
  验证一颗二叉树 是否是 二叉搜索树
1Solution <递归> Accepted / Used 时空复杂度 O(n) O(n)

/*
static T f() {
    前溯
    f()
    回溯
    return T;
}
BST,左子树的val< 根结点的val < 右结点的val
  利用中序遍历,我们可以知道搜索的顺序过程中,节点.val是升序的
  我们记max为历史节点.val的最大值,,如果当前结点.val > max, 满足条件 or 当前结点.val <= max不满足,递归结束
  其他细节如下:
*/
class Solution {
    static long max = Long.MIN_VALUE;
    static boolean f(TreeNode root) {
        if(root==null) return true;
        boolean b = f(root.left);
        if(max>=root.val) b = false;//=也不行
        max = Math.max(max,root.val);
        return b&&f(root.right); 
    }
    public boolean isValidBST(TreeNode root) {
        max = Long.MIN_VALUE;
        return f(root);
    }
}

1Solution <递归(官方)> Accepted / Used 时空复杂度 O(n) O(n)
// 根节点也可以为两个子树的判断提供(min,val),(val,max)条件, 遍历的是先序遍历


class Solution {
    public boolean isValidBST(TreeNode root) {
        return f(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    public boolean f(TreeNode root, long max, long min) {
        if (root == null) 
        	return true;
        if (root.val <= max || root.val >= min) 
            return false;
        return f(root.left, max, root.val) && f(root.right, root.val, min);
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值