LeetCode 098 Validate Binary Search Tree

题目


验证BST

代码1


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

根据定义,可以递归判断来完成。可是碰到问题,用Integer.MIN_VALUE等来判断,如果碰到root.val= Integer.MIN_VALUE会失效。

所以我们用了Long来判断。可是好的coder不会这么做。

于是有了新的写法

public class Solution {
    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        
        return useme(root, null,null);
    }
    
    public boolean useme(TreeNode root, Integer min ,Integer max){
        if(root == null){
            return true;
        }
        Integer val  = root.val;
        if(min!=null && val.compareTo(min)<=0){
            return false;
        }
        if(max!=null && val.compareTo(max)>=0){
            return false;
        }
        return useme(root.left,min,val) && useme(root.right,val,max);
    }
}
利用Integer包装类的compareTo的方法。这样一开始null的时候可以带入,但不用判断。

另外也可以用中序遍历的方法来比较,这样就不要考虑root的corner问题了。

public class Solution {
    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        
        List<Integer> record = new ArrayList<Integer>();
        useme(record,root);
        for(int i =1;i<record.size();i++){
            if(record.get(i-1)>=record.get(i)){
                return false;
            }
        }
        return true;
    }
    
    public void useme(List<Integer> record, TreeNode root){
        if(root!=null){
            useme(record,root.left);
            record.add(root.val);
            useme(record,root.right);
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值