Is This a Binary Search Tree?

  • + 19 comments

    Well , I just did an inorder traversal, stored them in a list and checked if they are in ascending order. If yes, then its a BST , else it isn't.

    This would work for all values (signed or unsigned) a node can possess.

    When compared with recursion (which has stack depth), space complexity remains the same in worst case.

    Time complexity also remains O(n) , only difference being that mine is a 2-pass solution.

    • + 1 comment

      I did the same

      • + 0 comments

        Even I did the same!!

    • + 0 comments

      I did this as well!

    • + 2 comments

      I used the same method like you, but I passed all solutons. However, I have no idea why my recusive method can't pass all.

      • + 1 comment

        Can you share your recursive code ?

        • + 2 comments

          Hey ,Even I tried the recursive method but all the test cases didnt pass, Please check the code

          bool checkBST(Node* root)
             {
                struct Node *tmp=(struct Node*)malloc(sizeof(struct Node));
                 tmp=root;
                 if(root==NULL)
                    return true;
                 else if(tmp->left!=NULL && tmp->right!=NULL)
                {
                if(tmp->data > (tmp->left)->data && tmp->data< (tmp->right)->data)
                  {
                     bool ans1=checkBST(tmp->left);
                     bool ans2=checkBST(tmp->right);
                      if(ans1 && ans2)
                          return true;
                      else return false;
                  }
                }
                 else if(tmp->left==NULL && tmp->right!=NULL)
                 {
                     if(tmp->data < (tmp->right->data))
                              return checkBST(tmp->right);
                     else return false;
                 }
                 else if(tmp->left!=NULL && tmp->right==NULL)
                 {
                     if(tmp->data > (tmp->left->data))
                         return checkBST(tmp->left);
                     else return false;
                 }
                 return true;
                  
             }
          
          • + 4 comments

            Consider the below 2 types of trees, you will know where you went wrong.

            Case 1 :

               20
              /  \
             10   2
            

            Case 2:

               18
              /  \
             8    20
                 /  \
                10  30
            
            • + 2 comments

              Alright I got it we have to find the minimum from left sub tree and the maximum from the right one Thanks!

              • + 2 comments

                Yes correct !

                • + 0 comments

                  Isn't it that all nodes in left tree should be less than root and right should be greater than root. Than why we need to find min and max.

              • + 0 comments

                Is it not the other way? minimum from right sub tree must be greater than root and maximum from left subtree must be less than root

            • + 0 comments

              Got it. thanks a lot.

            • [deleted]Challenge Author
              + 0 comments

              Thanks for case 2 visualization, this explains why my code failed a bunch of test cases.

            • + 0 comments

              Can anyone please tell me what's wrong in his code? What t understand from these two test-cases?

          • + 0 comments

            Queue ino=new LinkedList(); boolean checkBST(Node root) { inorder(root); int[] arr = ino.stream().mapToInt(i->i).toArray();//convert ArrayList to primitive int array int[] brr = ino.stream().mapToInt(i->i).toArray(); //ArrayList brr=new ArrayList(arr); Arrays.sort(arr); /* for(int i:arr) System.out.print(i+","); System.out.println(""); for(int i:brr) System.out.print(i+",");*/ if(Arrays.equals(arr,brr)) return true; else return false; } void inorder(Node root) { if(root==null) return; inorder(root.left); ino.add(root.data); inorder(root.right); }

      • + 2 comments

        Note, I haven't seen your code but here's a tip:

        You need to also think about all previous values higher in the tree, and not just the the current node, and the top of the left and right subtrees.

    • + 2 comments

      no need for a traversal. Take the node->data of each node directly from the vector values given in private. Rest logic is spot on. Did the same :)

      • + 0 comments

        This is great! I coded the solution to this problem in accordance with your comment!

        prevVal = -1
        resultVal = 1
        
        def check_binary_search_tree_(root):
          inOrder(root)
          if resultVal == 1:
            return True
          elif resultVal == 0:
            return False
        
        # perform an in order traversal 
        def inOrder(root):
          if root is None:
            return
          else:
            inOrder(root.left)
             
            global prevVal
            if prevVal < root.data:
              prevVal = root.data
            else:
              global resultVal
              resultVal = 0
              return
            
            inOrder(root.right)
        
      • + 0 comments

        My original solution is:

        def inOrder(root, stack=[]):
            if root.left:
                inOrder(root.left, stack)
            stack.append(root.data)
            if root.right:
                inOrder(root.right, stack)
        
                
        def check_binary_search_tree_(root):
            stack = []
            inOrder(root, stack)
            length = len(stack)
            for i in range(length-1):
                if stack[i] >= stack[i+1]:
                    return False
            return True
        

        With your comment, I coded the following solution in python3:

        flag = True
        pre = -1  # As all data are >= 0 so set pre = -1
        
        
        def inOrder(root):
            global flag, pre
            if root.left:
                inOrder(root.left)
            if pre < root.data:
                pre = root.data
            else:
                flag = False
                return
            if root.right:
                inOrder(root.right)
        
        
        def check_binary_search_tree_(root):
            inOrder(root)
            global flag
            return flag
        
    • + 1 comment

      I did a similar thing (except that the list was in descending order). My recursive algorithm had a flaw that appeared to be too difficult to waste time fixing.

      Note that I am more used to C so I didn't bother with the C++ libraries.

          struct List {
              int data;
              List *next;
          };
      
          List *makeDescendingList(Node *head, List *list) {
              List *newListNode;
              if (head == NULL) {
                  return list;
              } else {
                  list = makeDescendingList(head->left, list);
                  newListNode = new(List);
                  newListNode->data = head->data;
                  newListNode->next = list;
                  return makeDescendingList(head->right, newListNode);
              } 
          }
      
          bool isDescendingList (List *list) {
              while (list != NULL) {
                  if (list->next != NULL && list->data <= list->next->data) {
                      return false;
                  }
                  list = list->next;
              }
              return true;
          }
          
      	bool checkBST(Node* root) {
      		return isDescendingList(makeDescendingList(root, NULL));
      	}
      
      • + 3 comments

        You can just perform DFS and check if data is in ascending order. No additional data structures/parameters needed. Just one static variable (yep, I am a C programmer :))

        bool checkBST(Node* root) {
            static int last_visited = -2;
                if (!root) {
                    return true;
                }
                if (!checkBST(root->left)) {
                    return false;
                }
                if (root->data <= last_visited) {
                    return false;
                }
                last_visited = root->data;
                if (!checkBST(root->right)) {
                    return false;
                }
                return true;
        }
        
        • + 0 comments

          Great solution based on the constraints: 0 <= data <= 10^4. This is to utilize BST inorder traversal property. If the data can be min int, then the solution won't work.

        • + 0 comments

          This is a wonderful recursive solution.

        • + 0 comments

          Wow,,,, How could you tinker this method,, What a brilliant!

    • + 1 comment

      Inorder traversal of BST is always sorted. So you don't have to put elements into list. Store maximum element so far in a variable (say maxSoFar) and then just check if currentNode.data <= maxSoFar. It'll save you from iterating list.

      • + 0 comments

        thanks,

    • + 0 comments

      i tried same thing but many test cases fails... help me to come out plz.

    • + 1 comment

      I also did the same but some test cases are not working .Here my code- bool func(vector v) { int count=0; for(int i=0;i v; if(root==NULL) return true; if(root!=NULL) { checkBST(root->left); v.push_back(root->data); checkBST(root->right); } return func(v);

      }

      • + 0 comments

        You want this...

            static int min = -1;
            static boolean flag = true;
        
            public static void inOrder(Node root){ 
        
                if(root.left != null){
                    inOrder(root.left);
                }
                if(root.data <= min){
                    flag = false;
                }
                min = root.data;
                if(root.right != null){
                    inOrder(root.right);
                }
            }
            
            boolean checkBST(Node root) {
                inOrder(root);
                return flag;       
            }
        
    • + 0 comments

      did the same dude !!!!!! 2 cases failed in recursion,didn't know the reason and sample input was also confusing and accidentally i reached this solution while understanding the sample input ... ;)

    • + 1 comment

      You don't need to create list or array while doing inorder traversal. The whole point is to compare current and last element, if last elment is greater or equal to current return false. Just use one wrapper int, or Integer static variable to keep track of last visited.

      • + 1 comment

        But its not always true.

        Consider this case:

           18
          /  \
         8    20
             /  \
            10  30
        
        • + 1 comment

          This would return false. Inorder 8 -> 18 -> 10

          18 > 10

          As long as the last element is the last elemented "visited" and not last element passed by.

          • + 1 comment

            Yes, but as long as we return max values from left subtrees and min values from right subtrees and make sure they follow the rule.

            • + 1 comment

              I didn't do that. I just did inorder traversal recursively and made sure it was all ascending order. Passed all cases.

              • + 0 comments

                Mine is also a similar idea.

    • + 0 comments

      I think you can improve your space complexity only using a variable and comparing current node with his prev node.

    • + 0 comments

      Was able to solve it because of your comment. thanks a lot. Here's my code.

      static ArrayList<Integer> list = new ArrayList<Integer>();
          boolean checkBST(Node root) {
              
              inOrder(root);
              
              for(int i = 1; i< list.size(); i++){
                  if(list.get(i)<=list.get(i-1))
                      return false;
              }
              return true;
               
          }
          
          void inOrder(Node root){
              if(root == null)
                  return;
              inOrder(root.left);
              list.add(root.data);
              inOrder(root.right);
          }
      
    • + 0 comments

      Did the same thing.

    • + 1 comment

      I did the same. But it's not working.

      Here is my code. Can you review it please?

      vector <int> inorder_nodes;
      
      void Traverse_Inorder(Node *root)
      {
          if(root->left != NULL)
              Traverse_Inorder(root->left);
      
          inorder_nodes.push_back(root->data);
      
          if(root->right != NULL)
              Traverse_Inorder(root->right);        
      }
      
      bool checkBST(Node* root) {
      
          bool result=true;
      
          Traverse_Inorder(root);
      
          for (int i = 0; i < inorder_nodes.size(); i++)
          {
              if(inorder_nodes[i] > inorder_nodes[i+1])
              {
                  result = false;
                  break;
              }            
          }
      
          return result;
      
      }
      
      • + 0 comments

        Try this

        vector <int> inorder_nodes;
        
        void Traverse_Inorder(Node *root)
        {
            if(root == NULL) return;
            
            if(root->left != NULL)
                Traverse_Inorder(root->left);
            
            inorder_nodes.push_back(root->data);
        
            if(root->right != NULL)
                Traverse_Inorder(root->right);        
        }
        
        bool checkBST(Node* root) {
        
            Traverse_Inorder(root);
        
            for (int i = 0; i < inorder_nodes.size()-1; i++){
                if(inorder_nodes[i] >= inorder_nodes[i+1]) return false;
            }
            
            inorder_nodes.clear();
        
            return true;
        
        }
        
    • + 0 comments

      Isn't necessary to store the values in a list, just keep track of the previous visited value (inorder sequence), and if your current visiting value is less than it means that isn't a BST

    • + 0 comments

      Thanks for your insight! My code worked!