您的位置:首页 > 其它

基于Comparable接口实现的二叉树操作

2014-11-26 00:00 281 查看
摘要: 我也不太懂,没看明白

class BinaryTree

{

class Node

{

private Comparable date;

private Node left;

private Node right;

public void addNode(Node newNode)

{

if (newNode.date.compareTo(this.date)<0)

{

if (this.left == null)

{

this.left= newNode;

} else

{

this.left.addNode(newNode);

}

}

if (newNode.date.compareTo(this.date)>=0)

{

if (this.right==null)

{

this.right= newNode;

} else

{

this.right.addNode(newNode);

}

}

}

public void printNode()

{

if (this.left!= null)

{

this.left.printNode();

}

System.out.print(this.date + "\t");

if(this.right != null)

{

this.right.printNode();

}

}

}

private Node root;

public void add(Comparable date )

{

Node newNode= new Node();

newNode.date=date;

if (root== null)

{

root= newNode;

} else

{

root.addNode(newNode);

}

}

public void print()

{

this.root.printNode();

}

}

public class ComparableDemo3

{

/**

* @param args

*/

public static void main(String[] args)

{

BinaryTree bt = new BinaryTree();

bt.add(8);

bt.add(2);

bt.add(4);

bt.add(6);

bt.add(0);

bt.add(7);

bt.add(9);

bt.add(1);

System.out.print("排序后的结果:");

bt.print();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: