本程序需要上一篇博客代碼支持,詳見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(); } }