Java - Very clear & easy solution using INT_MAX and INT_MIN


  • 1
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root == null) return true;
            
            return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }
        
        private boolean isValidBST(TreeNode root, long min, long max){
            if( root == null) return true;
            if(!inRange(root.val,min,max)) return false;
            
            boolean left = isValidBST(root.left, min, (long)root.val);
            boolean right = isValidBST(root.right, (long)root.val, max);
            
            return left && right;
        }
        
        private boolean inRange(int val, long min, long max){
            return (val>min && val<max) ;
        }
    }
    

Log in to reply
 

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