Skip to content

Instantly share code, notes, and snippets.

@chouclee
Created July 14, 2014 15: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 chouclee/27641529cf8c80d2bff4 to your computer and use it in GitHub Desktop.
Save chouclee/27641529cf8c80d2bff4 to your computer and use it in GitHub Desktop.
[CC150][4.5] Implement a function to check if a binary tree is a binary search tree.
// traverse the tree in order
public class isBST<Key extends Comparable<Key>> {
private Node<Key> prev;
public boolean check(Node<Key> node) {
prev = null;
return isBst(node);
}
private boolean isBst(Node<Key> x) {
if (x == null) return true;
if (!isBst(x.left))
return false;
if (prev != null && prev.key.compareTo(x.key) > 0)
return false;
prev = x;
System.out.println(prev.key);
return (isBst(x.right));
}
public static void main(String[] args) {
isBST<Integer> test = new isBST<Integer>();
Node<Integer> root = new Node<Integer>(0);
root.left = new Node<Integer>(2);
root.left.left = new Node<Integer>(1);
root.left.right = new Node<Integer>(3);
root.right = new Node<Integer>(6);
root.right.left = new Node<Integer>(5);
root.right.right = new Node<Integer>(8);
if (test.check(root))
System.out.println("Yes");
else System.out.println("No");
}
}
public class Node<Key> {
public Key key;
public Node<Key> left, right;
public Node(Key key) {
this.key = key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment