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);
}