Skip to content

Instantly share code, notes, and snippets.

@jimod
Created August 18, 2015 15:01
Show Gist options
  • Save jimod/785b9b75f716c7501e11 to your computer and use it in GitHub Desktop.
Save jimod/785b9b75f716c7501e11 to your computer and use it in GitHub Desktop.
class TreeSet<T extends Comparable<T>> {
private static class Node<T> {
T item;
Node<T> left, right;
Node(T item0, Node<T> left0, Node<T> right0) {
item = item0; left = left0; right = right0;
}
}
private Node<T> root = null;
private int numItems = 0;
public TreeSet() {
root = new Node<T>(null, null, null);
numItems = 0;
}
public TreeSet(T t) {
root = new Node<T>(t, null, null);
numItems = 1;
}
public boolean contains(T t){
Node<T> currentNode = root;
boolean found = false;
for(int i = 0; i <= numItems; i++){
if(currentNode.item.compareTo(t) == 0)
{
found = true;
}
else
{
if(currentNode.item.compareTo(t) > 0)
{
currentNode = currentNode.left;
}
else if(currentNode.item.compareTo(t) < 0)
{
currentNode = currentNode.right;
}
}
if(currentNode == null)
{
return false;
}
}
return found;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment