Test case fails


  • 0
    V
    public boolean isValidBST(TreeNode root) {
            
            if(root == null){
                return true;
            }
            
            if(root.left == null && root.right == null){
                return true;
            }
        
            if(isValidBST(root.left) && isValidBST(root.right))
            {
                if(root.left!=null && root.right!=null && root.left.val <= root.val && root.right.val > root.val){ 
                    return true;
                }else if(root.left == null && root.right.val > root.val){
                    return true;
                }else if(root.right == null && root.left.val <= root.val){
                    return true;
                }else{
                    return false;
                }
            }
            
            return false;
            
        }
    

    64 / 74 test cases passed.

    Input:
    [1,1]
    Output:
    true
    Expected:
    false


  • 0

    Not sure what your point is. Are you asking how to fix your solution?


  • 0
    V

    @StefanPochmann....My code seems right to me. but this test case fails, I am trying to figure out why test case fails..do u find anything wrong in code?


  • 0

    That tree is so small that you should really be able to just think through what your code does with it.


  • 1
    S
    // For this question it is suggested that left node will have value strictly lesser than 
    // current node and right node will have value strictly greater than the current value. 
    // In your algorithm, Following statement
    // root.left.val <= root.val allows the left node to have same value as root node.
    // That's why it fails at that test case.
    // Following is a code which covers all the test case.
    
    public boolean isValidBST(TreeNode root) {
                return validBST(root, Integer.MAX_VALUE, Integer.MIN_VALUE);
            }
    public boolean validBST(TreeNode curr, int max, int min){
                if(curr == null)
                    return true;
                if((curr.val == Integer.MIN_VALUE && curr.left!=null) || (curr.val == Integer.MAX_VALUE && curr.right!=null))
                    return false;
                if(curr.val>=min && curr.val<=max)
                    return (((curr.left==null)?true:validBST(curr.left,curr.val-1, min)) && ((curr.right==null)?true:validBST(curr.right, max, curr.val+1)));
                else
                    return false;
            }

  • 0
    K
    This post is deleted!

Log in to reply
 

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