Check if the given binary tree is BST or not.
public static boolean isBST(BST root, int min, int max)
{
if (root == null)
{
return true;
}
// initialize min
TreeNode ptr = root;
while (ptr.left != null)
{
ptr = ptr.left;
}
Integer min = ptr.element;
// initialize max
ptr = root;
while (ptr.right != null)
{
ptr = ptr.right;
}
Integer max = ptr.element;
return isBST_helper(root, min, max);
}
private boolean isBST_helper(TreeNode node, Integer min, Integer max)
{
if (node == null)
return true;
if (node.element > max || node.element < min)
{
return false;
}
return isBST_helper(node.left, min, node.element - 1)
&& isBST_helper(node.right, node.element + 1, max);
}