Skip to content

Instantly share code, notes, and snippets.

@manuel-sugawara
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuel-sugawara/9592308 to your computer and use it in GitHub Desktop.
Save manuel-sugawara/9592308 to your computer and use it in GitHub Desktop.
Write a function that returns whether a given binary tree is a valid binary search tree.
/**
* Returns {@code true} if the node is the root of a vaild binary
* search tree.
*/
public static boolean isBinarySearchTree(Node<T extends Comparable> node) {
if (node == null) {
return true;
}
if (node.left == null && node.right == null) {
return true;
}
if (node.left != null && node.left.value.compareTo(node.value) > 0) {
return false;
}
if (node.right != null && node.right.value.compareTo(node.value) < 0) {
return false;
}
return isBinarySearchTree(node.left) && isBinarySearchTree(node.right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment