本程序需要上一篇博客代码支持,详见java比较器的应用
package comparabledemo; class Node { private Comparable data; private Node left; private Node right; public Node() { super(); } public Node(Comparable data) { super(); this.data = data; } /** 添加接点 */ @SuppressWarnings("unchecked") public void addNode(Node n) { /** 添加左子树 */ if (this.data.compareTo(n.data) < 0) { if (this.left == null) { this.left = n; } else { this.left.addNode(n); } /** 添加右子树 */ } else{ // if (this.data.compareTo(n.data) >= 0) if (this.right == null) { this.right = n; } else { this.right.addNode(n); } } } /** !输出接点 */ public void printNode() { if (this.left != null) { this.left.printNode(); } System.out.println(this.data); if (this.right != null) { this.right.printNode(); } } } public class BinaryTree { private Node root; // 打印树的内容 public void print() { this.root.printNode(); } // 添加元素 public void add(Comparable d) { Node newNode = new Node(d); if (root == null) { root = newNode; } else { root.addNode(newNode); } } public static void main(String[] args) { BinaryTree btree=new BinaryTree(); Comparable<StudentCompare> s1 = new StudentCompare("李成明", 55100617); Comparable<StudentCompare> s2 = new StudentCompare("王瑶", 55100619); Comparable<StudentCompare> s3 = new StudentCompare("李大鹏", 55100614); Comparable<StudentCompare> s4 = new StudentCompare("赵国良", 55100613); Comparable<StudentCompare> s5 = new StudentCompare("赵国良", 55100613); Comparable<StudentCompare> s6 = new StudentCompare("胖子", 55100607); Comparable<StudentCompare> s7 = new StudentCompare("白胖", 55100623); btree.add(s1); btree.add(s2); btree.add(s3); btree.add(s4); btree.add(s5); btree.add(s6); btree.add(s7); // btree.add(5); // btree.add(4); // btree.add(8); // btree.add(6); // btree.add(4); // btree.add(3); btree.print(); } }