import java.util.*;
class TreeeSet<E> {
class Node {
Node(E value) {this.value = value;}
E value;
Node left, right;
void add(Node n, Comparator<E> comparator) {
if (n == null || comparator == null) return;
int c = comparator.compare(this.value, n.value);
if (c < 0) { // this < n
if (right == null) right = n; else right.add(n, comparator);
} else if (c > 0){
if (left == null) left = n; else left.add(n, comparator);
} else {/* nop */}
}
List<E> inject(List<E> list) {
if (left != null) left.inject(list);
list.add(value);
if (right != null) right.inject(list);
return list;
}
private Node removedright() {Node removed = right;right = null;return removed;}
private Node removedleft() {Node removed = left;left = null;return removed;}
Node remove(E value, Comparator<E> comparator) {
if (value == null || comparator == null) return null;
int c = comparator.compare(this.value, value);
if (c < 0 && right != null) { // this.value < value
return comparator.compare(right.value, value) == 0 ? removedright() : right.remove(value, comparator);
} else if (c > 0 && left != null) {
return comparator.compare(left.value, value) == 0 ? removedleft() : left.remove(value, comparator);
}
return null;
}
}
public TreeeSet(Comparator<E> comparator) {
this.comparator = comparator;
}
public Comparator<E> comparator() {return comparator;}
public void add(E value) {
if (value == null) {
// nop
} else if (root == null) {
root = new Node(value);
} else {
root.add(new Node(value), comparator);
}
}
private boolean changeroot(Node master, Node slave) {
root = master;
if (root != null) root.add(slave, comparator);
return true;
}
private boolean removeroot() {
return root.left != null
? changeroot(root.left, root.right)
: changeroot(root.right, root.left)
;
}
private int cmp(E a, E b) {
return comparator.compare(a, b);
}
private boolean removenode(E value) {
Node removed = root.remove(value, comparator);
if (removed != null) {
root.add(removed.left, comparator);
root.add(removed.right, comparator);
return true;
}
return false;
}
public boolean remove(E value) {
if (root == null || value == null) return false;
return cmp(root.value, value) == 0 ? removeroot() : removenode(value);
}
public Iterator<E> iterator() {
return root != null ? root.inject(new ArrayList<E>()).iterator() : new ArrayList<E>().iterator();
}
private Node root;
private Comparator<E> comparator;
}
class Qz4_403 {
public static void main
(String[] args
) { int N = 10, MAX = 1000;
TreeeSet<Integer> tree = new TreeeSet<Integer>(new Comparator<Integer>() {
return o1.compareTo(o2);
}
});
for (int i = 0; i < N; i++) {
tree.
add(new Integer(random.
nextInt(MAX
))); }
for (Iterator<Integer> it = tree.iterator(); it.hasNext();) {
System.
out.
println(it.
next()); }
}
}