Skip to content

Instantly share code, notes, and snippets.

@jimod
Created August 18, 2015 15:01
Show Gist options
  • Select an option

  • Save jimod/785b9b75f716c7501e11 to your computer and use it in GitHub Desktop.

Select an option

Save jimod/785b9b75f716c7501e11 to your computer and use it in GitHub Desktop.

Revisions

  1. jimod created this gist Aug 18, 2015.
    56 changes: 56 additions & 0 deletions TreeSet.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    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;
    }
    }