反转二叉树 java_反转二叉树【Java】

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());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值