Very Short and Concise Java solution (Easy to understand!)


  • 7
    M
        public boolean isValidBST(TreeNode root) {
            return validateRange(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }
     
        private boolean validateRange(TreeNode root, long min, long max) {
            if (root == null) return true;
            if (!(root.val > min && root.val < max)) return false;
            return validateRange(root.left, min, (long) root.val) 
            && validateRange(root.right, (long) root.val, max);
        }
    

    We take advantages on the constraint of the range for the value in a BST.


  • 0
    B

    What if the value of the node is designed to be long?


  • 0
    M

    You may be able to use null values to represent the unlimited boundaries.


  • 0
    B

    But then we may not distinguish the min and max, may we?


Log in to reply
 

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