1

I am trying to check whether a given binary tree is a Binary Search Tree or not. What I am trying to do is perform an inorder traversal of the binary tree and compare the current element with the previous element. In case the current element is greater we go on and check further else the given tree is invalid.

int prev=0;
public int isValidBST(TreeNode A) {
    if(A==null)
    return 1;
    isValidBST(A.left);
  //  System.out.println("val "+A.val);
   if(A.val<=prev)
   return 0;
   // else if(A!=null){
    prev=A.val;

    //System.out.println("prev "+prev);
    isValidBST(A.right);
    if(isValidBST(A.right)==1&&isValidBST(A.left)==1)
    return 1;
    return 0;
}

So this is the code that I have written. What I am doing wrong here?

halfer
  • 19,824
  • 17
  • 99
  • 186
Arsh Thind
  • 21
  • 1
  • 4
  • 1
    Why are you using 0/1 instead of boolean? – Andy Turner Jan 24 '18 at 09:19
  • calling isValidBST twice for left and right is bound to create havoc with your global variable. – laune Jan 24 '18 at 09:21
  • Could you provide an example of a case where your code does not produce the correct output (in other words, an [MCVE](https://stackoverflow.com/help/mcve))? – ash Jan 24 '18 at 09:21

2 Answers2

1

Only one recursive call per subtree! Use boolean!

int prev=0;
public boolean isValidBST(TreeNode A) {
    if( A == null ) return true;
    if( ! isValidBST(A.left) ) return false;
    if( A.val <= prev ) return false;
    prev = A.val;
    if( ! isValidBST(A.right) ) return false;
    return true;
}
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
laune
  • 31,114
  • 3
  • 29
  • 42
1
  1. suggestion: You can make your method return boolean instead of int.
  2. Also, I prefer to take a null node instead of an variable. This way you can make your tree storing -ve values and other than integers too(just need to change comparison logic).
  3. If you want your tree to have non-distinct values too, then you can remove the equal sign from node.data <= prev.data

    TreeNode prev=null;
    public boolean isValidBST(TreeNode node)
    {
        //null is a valid bst
        if(node==null){
            return true;
        }
    
        // traverse the tree in inorder fashion and
        // keep a track of previous node
        if (!isValidBST(node.left)){
            return false;
          }
    
        // compare current data with previous one
       if (prev != null && node.data <= prev.data){
           return false;
       }
    
       prev = node;
    
       //check right subtree
       return isValidBST(node.right);
    }
    
Priya Jain
  • 795
  • 5
  • 15