Simple recursive solution with comments


  • 0
    1
    public boolean isValidBST(TreeNode root) {
        return checkBST(root, null, null);
    }
    
    public boolean checkBST(TreeNode node, Integer min, Integer max) {
        // An empty tree is a valid tree
        if(node == null)
            return true;
    
        //If min or max is null, consider it valid. If not, compare it with the node value
        if((min == null || node.val > min) && (max == null || node.val < max))
            return checkBST(node.left, min, node.val) &&
                    checkBST(node.right, node.val, max);
        
        return false;
    
    }

Log in to reply
 

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