packagecom.example.demo.tree;importcom.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;importorg.omg.PortableInterceptor.INACTIVE;importjava.util.Comparator;/***@authorsteve
* @date 2020/4/16 10:03 上午*/
public class BinaryTree{private intsize;public Noderoot;private Comparatorcomparator;public BinaryTree(Comparatorcomparator){this.comparator =comparator;
}publicBinaryTree(){this(null);
}public voidadd(E element){if (root == null){
Node node= newNode(element);
root=node;
}else{
Node parent =root;
Node node =root;int com = 0;while (node != null){
parent=node;if (comparator == null){
com=((Comparable)node.element).compareTo(element);
}else{
System.out.println("-------------");
com=comparator.compare(node.element,element);
}if (com > 0){
node=node.left;
}else if (com < 0){
node=node.right;
}else{
node.element=element;return;
}
}
Node newNode = newNode(element);if (com > 0){
parent.left=newNode;
newNode.parent=parent.left;
}else{
parent.right=newNode;
newNode.parent=parent.right;
}
}
size++;
}public booleanisEmpty(){return size == 0;
}public intsize(){returnsize;
}publicString toString() {
String d= root == null ? null : root.element + "";if (root == null){return "root:"+d;
}else{
String b= root.left == null ? null : root.left.element + "";
String c= root.right == null ? null : root.right.element + "";return "root:"+d + ", left:" + b + ", right:"+c;
}
}public static voidmain(String[] args) {//这种方式就是匿名内部类,通过给一个类传一个接口作为参数,然后这个通过一个匿名内部类是实现这个接口来传入实现。
BinaryTree binaryTree = new BinaryTree<>(new Comparator() {
@Overridepublic intcompare(Integer o1, Integer o2) {return o1 -o2;
}
});
BinaryTree binaryTree1 = new BinaryTree<>();
binaryTree1.add(1);
binaryTree1.add(2);
binaryTree1.add(0);
System.out.println(binaryTree1.size());
System.out.println(binaryTree.toString());
}
}