Java Soln


  • 0
    G
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution 
    {
        public boolean isValidBST(TreeNode root) 
        {
            if(root==null)
                return true;
            
            return isValidBST(root, 0, 0, false, false);
        }
        
        public boolean isValidBST(TreeNode root, int min, int max, boolean minValid, boolean maxValid) 
        {
            
            if((minValid==true)&&(root.val<=min))
                return false;
            if((maxValid==true)&&(root.val>=max))
                return false;
            
            boolean left = true;
            boolean right = true;
            if(root.left!=null)
                left = isValidBST(root.left, min, root.val, minValid, true);
            if(root.right!=null)
                right = isValidBST(root.right, root.val, max, true, maxValid);
            
            return (left & right);
        }
        
       
    }
    

Log in to reply
 

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