代码实现:
1 package cn.demo; 2 3 class Phone implements Comparable <Phone> { 4 private String brand ; 5 private double price ; 6 public Phone(String brand,double price) { 7 this.brand = brand ; 8 this.price = price ; 9 } 10 @Override 11 public String toString() { 12 return "品牌:" + this.brand + ",价格:" + this.price + " " ; 13 } 14 @Override 15 public int compareTo(Phone o) { 16 if (this.price > o.price) { 17 return 1 ; 18 } else if (this.price < o.price) { 19 return -1 ; 20 } else { 21 return 0 ; 22 } 23 } 24 } 25 class BinaryTree { 26 // 不管是什么数据结构一定要求有Node类 27 private class Node { 28 @SuppressWarnings("rawtypes") 29 private Comparable data ; 30 private Node left ; 31 private Node right ; 32 @SuppressWarnings("rawtypes") 33 public Node(Comparable data) { 34 this.data = data ; 35 } 36 public void addNode(Node newNode) { 37 if (newNode.data.compareTo(this.data) < 0) { 38 if (this.left == null) { // 现在左边没有数据 39 this.left = newNode ; 40 } else { 41 this.left.addNode(newNode); 42 } 43 } else { 44 if (this.right == null) { 45 this.right = newNode ; 46 } else { 47 this.right.addNode(newNode); 48 } 49 } 50 } 51 public void toArrayNode() { 52 if (this.left != null) { 53 this.left.toArrayNode(); 54 } 55 BinaryTree.this.retObj [BinaryTree.this.foot ++] = this.data ; 56 if (this.right != null) { 57 this.right.toArrayNode(); 58 } 59 } 60 } 61 // 编写BinaryTree中的程序代码,任何的节点操作离不开根节点 62 private Node root ; // 定义根节点,第一个保存的数据作为根节点 63 private int count ; 64 private int foot ; 65 private Object retObj [] ; // 设置返回的数据 66 public void add(Object obj) { 67 if (obj == null) { 68 return ; 69 } 70 Node newNode = new Node((Comparable) obj) ; 71 if (this.root == null) { // 现在没有根节点 72 this.root = newNode ; 73 } else { // 如果有根节点,需要判断其保存的位置 74 this.root.addNode(newNode) ; 75 } 76 this.count ++ ; 77 } 78 public int size() { 79 return this.count ; 80 } 81 public Object [] toArray() { 82 if (this.count == 0) { 83 return null ; 84 } 85 this.retObj = new Object [this.count] ; 86 this.foot = 0 ; 87 this.root.toArrayNode() ; 88 return this.retObj ; 89 } 90 } 91 92 public class Test { 93 public static void main(String[] args) { 94 BinaryTree bt = new BinaryTree() ; 95 bt.add(new Phone("黑米",799.00)); 96 bt.add(new Phone("白米",399.00)); 97 bt.add(new Phone("紫米",899.00)); 98 System.out.println(bt.size()); 99 Object obj [] = bt.toArray() ; 100 for (int x = 0 ; x < obj.length ; x ++) { 101 System.out.println(obj[x]); 102 } 103 } 104 }
输出结果:
3
品牌:白米,价格:399.0
品牌:黑米,价格:799.0
品牌:紫米,价格:899.0