Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hackerrank: Is This a Binary Tree?

Problem Statement: https://www.hackerrank.com/challenges/is-binary-search-tree

My Solution:

boolean checkBST(Node root) {
    if(root == null || (root.left == null && root.right == null)) {
        return true;
    } else if(root.left != null && root.right == null) {
        return (root.data > root.left.data) && checkBST(root.left);
    } else if(root.right != null && root.left == null) {
        return (root.data < root.right.data) && checkBST(root.right);
    } else {
        return (root.data > root.left.data) && (root.data < root.right.data) && checkBST(root.left) && checkBST(root.right);
    }
}

Getting "Wrong Answer" for few of the test cases. I know there are a lot of ways to solve this problem, but I am trying to figure out the error in the above solution.

Note: I am not able to debug for those specific test cases because the code doesn't show how the BST is built with those testcases.

Edit: working solution:

  boolean bstUtil(Node root, int min, int max) {
            return root == null 
                || (root.data > min && root.data < max) 
                && bstUtil(root.left, min, root.data) 
                && bstUtil(root.right, root.data, max);
   }

   boolean checkBST(Node root) {
        return bstUtil(root, -1, 10001);
   }
like image 233
Abhishek Avatar asked Sep 13 '26 21:09

Abhishek


1 Answers

Consider the following tree :

             3
            / \
           2   5
          / \
         1   6

Your test would return true, even though this is not a binary search tree (since the left sub-tree of the root contains a node (6) larger than the root (3)).

It's not enough to check that the left sub-tree is a binary search tree and the left child is smaller than the root. You must also check that every node of the left child is smaller than the root.

like image 132
Eran Avatar answered Sep 16 '26 10:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!