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

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

}

}


你可能感兴趣的:(基于Comparable接口实现的二叉树操作)