import java.util.ArrayList;
import java.util.List;
public class BinaryTree<T extends Comparable> {
class Node {
private Node left;
private Node right;
private T data;
private boolean distinct;
public Node(T data, boolean distinct){
this.data = data;
this.distinct = distinct;
}
public void addNode(Node newNode) {
int compare = newNode.data.compareTo(this.data);
if (compare < 0) {
if (this.left == null) {
this.left = newNode;
} else {
this.left.addNode(newNode);
}
return;
}
if (compare > 0 || !this.distinct) {
if (this.right == null) {
this.right = newNode;
} else {
this.right.addNode(newNode);
}
return;
}
}
public void toList(List<T> list){
if (this.left != null) {
this.left.toList(list);
}
list.add(this.data);
if (this.right != null) {
this.right.toList(list);
}
}
}
private Node root;
private boolean distinct;
public BinaryTree() {
this.distinct = false;
}
public BinaryTree(boolean distinct) {
this.distinct = distinct;
}
public List<T> sort(Iterable<T> iterable) {
for (T data : iterable){
Node newNode = new Node(data, this.distinct);
if (this.root == null) {
this.root = newNode;
} else {
this.root.addNode(newNode);
}
}
List<T> result = new ArrayList<>();
if (this.root == null) {
return result;
}
this.root.toList(result);
return result;
}
public static void main(String[] args){
List<String> list = Arrays.asList("EE", "BB", "AA","AA","BB");
BinaryTree<String> bt = new BinaryTree(true);
List<String> result = bt.sort(list);
for (String k : result){
System.out.println(k);
}
}
}