Java 3 lines solution without using long or global variable


  • 0

    ub := use upper bound
    lb := use lower bound

        public boolean isValidBST(TreeNode root) {
            return rec(root, 0, 0, false, false);
        }
    
        private boolean rec(TreeNode root, int min, int max, boolean lb, boolean ub) {
            if (root == null) return true;
            if (lb && root.val <= min || ub && root.val >= max) return false;
            return rec(root.left, min, root.val, lb, true) && rec(root.right, root.val, max, true, ub);
        }
    

Log in to reply
 

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