1ms Java Solution


  • 0
    P
    public class Solution {
        
        public boolean mintrue = false, maxtrue = false;
        public boolean isValidBST(TreeNode root) {
           
            return isValid(root,Integer.MIN_VALUE,Integer.MAX_VALUE);
           
        }
        
        
        public boolean isValid(TreeNode root,int min,int max){
            if(root==null)return true;
            if(root.val==Integer.MIN_VALUE&&mintrue||root.val==Integer.MAX_VALUE&&maxtrue)return false;
            if(root.val==Integer.MIN_VALUE)mintrue = true;if(root.val==Integer.MAX_VALUE)maxtrue = true;
            if((root.val<=min&&min!=Integer.MIN_VALUE)||(root.val>=max&&max!=Integer.MAX_VALUE))return false;
            if(root.left==null&&root.right==null)return true;
            if(root.left!=null&&root.val<=root.left.val)return false;
            if(root.right!=null&&root.val>=root.right.val)return false;
            if(!isValid(root.left,min,root.val)||!isValid(root.right,root.val,max))return false;
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.