package java.util; public class TreeSet implements Iterable { private final Comparator comparator; private int size; private Cell root; public TreeSet(Comparator comparator) { this.comparator = comparator; size=0; root=null; } public Iterator iterator() { return walk().iterator(); } private ArrayList walk() { return walk(root, new ArrayList(size)); } private ArrayList walk(Cell cell, ArrayList list) { if (cell != null) { walk(cell.left, list); list.add(cell.value); walk(cell.right, list); } return list; } public boolean add(T o) { ++size; if (root == null) { root = new Cell(o); return true; } else { Cell newElt = new Cell(o); Cell cur = root; do { int result = comparator.compare(o, cur.value); if (result == 0) return false; if (result < 0) { if (cur.left == null) { newElt.parent = cur; cur.left = newElt; return false; } else { cur = cur.left; } } else { if (cur.right == null) { newElt.parent = cur; cur.right = newElt; return false; } else { cur = cur.right; } } } while (cur != null); throw new RuntimeException("Fell off end of TreeSet"); } } public boolean remove(T o) { throw new UnsupportedOperationException(); } public int size() { return size; } private static class Cell { public final T value; public Cell parent; public Cell left; public Cell right; public Cell(T val) { value = val; } } }