Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active August 29, 2015 14:25
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 danieldietrich/9a43c087089059b71ed3 to your computer and use it in GitHub Desktop.
Save danieldietrich/9a43c087089059b71ed3 to your computer and use it in GitHub Desktop.
Checks if a binary tree is a binary search tree
class BinaryTree<T> extends Tree<T> {
// ...
default boolean isBinarySearchTree() {
class MinMax<U extends Comparable<Object>> {
final U min;
final U max;
MinMax(U min, U max) {
this.min = min;
this.max = max;
}
boolean isMaxLessThan(U value) {
return isEmpty() || max.compareTo(value) < 0;
}
boolean isMinGreaterThan(U value) {
return isEmpty() || min.compareTo(value) > 0;
}
boolean isEmpty() {
return min == null && max == null;
}
MinMax<U> minMax(MinMax<U> that) {
if (isEmpty()) {
return that;
} else if (that.isEmpty()) {
return this;
} else {
return new MinMax<>(this.min, that.max);
}
}
}
class Machine<U extends Comparable<Object>> {
final Some<MinMax<U>> EMPTY = new Some<>(new MinMax<>(null, null));
Option<MinMax<U>> compute(BinaryTree<U> tree) {
if (tree.isEmpty()) {
return EMPTY;
} else {
final U value = tree.getValue();
if (tree.isLeaf()) {
return new Some<>(new MinMax<>(value, value));
} else {
return compute(tree.left()).flatMap(left ->
compute(tree.right()).flatMap(right -> {
if (left.isMaxLessThan(value) && right.isMinGreaterThan(value)) {
return new Some<>(left.minMax(right));
} else {
return None.instance();
}
})
);
}
}
}
}
@SuppressWarnings("unchecked")
final Try.CheckedSupplier<Boolean> computation = () ->
new Machine<>().compute((BinaryTree<Comparable<Object>>) this).isDefined();
return Try.of(computation).orElse(false);
}
}
import static javaslang.collection.BinaryTree.*;
public class Test {
public static void main(String[] args) {
{ // test 1
final BinaryTree<Integer> tree = branch(leaf(10), 20, branch(leaf(5), 30, leaf(40)));
System.out.println(tree.toLispString()); // (20 10 (30 5 40))
System.out.println(tree.isBinarySearchTree()); // false
}
{ // test 2
final BinaryTree<Integer> tree = branch(leaf(10), 20, branch(leaf(25), 30, leaf(40)));
System.out.println(tree.toLispString()); // (20 10 (30 25 40))
System.out.println(tree.isBinarySearchTree()); // true
}
{ // test 3
final BinaryTree<?> tree = branch(leaf(10.0), 20, branch(leaf(25), 30, leaf(40)));
System.out.println(tree.toLispString()); // (20 10.0 (30 25 40))
System.out.println(tree.isBinarySearchTree()); // false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment