This is my solution to challenge “Trees: Is This a Binary Search Tree?” on HackerRank. Click here to see the challenge.
import java.io.*;
/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.
The Node class is defined as follows:
class Node {
int data;
Node left;
Node right;
}
*/
boolean checkBST(Node root) {
return checkBSTRecursive(root,Integer.MIN_VALUE, Integer.MAX_VALUE);
}
boolean checkBSTRecursive(Node root, int min, int max) {
if(root == null){
return true;
}
if(root.data < min || root.data > max){
return false;
}
if(root.left != null && root.right != null){
if(root.left.data > root.data || root.right.data < root.data){
return false;
}
}
return checkBSTRecursive(root.left,min, root.data-1) && checkBSTRecursive(root.right,root.data+1,max);
}