import java.util.Arrays;
public class TestDemo {
static class Food implements Comparable<Food>{
private String name;
private int calories;
public Food(String name, int calories) {
this.name = name;
this.calories = calories;
}
@Override
public String toString() {
return "名称:"+this.name+", 热量:"+this.calories+"\n";
}
@Override
public int compareTo(Food o) {
return this.calories-o.calories;
}
}
static class BinaryTree{//二叉树的实现
private class Node{//数据接狗狗必须有Node类,负责保存数据以节点的关系匹配
private Comparable data;
private Node left;
private Node right;
@SuppressWarnings("rawtypes")
public Node( Comparable data) {
this.data = data;
}
@SuppressWarnings("unchecked")
public void addNode(Node newNode) {
if(this.data.compareTo(newNode.data)>0) { //保存在左边
if(this.left == null) {
this.left = newNode;
}else {
this.left.addNode(newNode);
}
}else {
if(this.right == null ) {
this.right = newNode;
}else {
this.right.addNode(newNode);
}
}
}
public void toArrayNode() {
if(this.left != null) {//有左节点
this.left.toArrayNode();
}
BinaryTree.this.retData[BinaryTree.this.foot++] = this.data;
if(this.right!= null) {
this.right.toArrayNode();
}
}
}
//**************** 编写BinaryTree操作 *****************
private Node root; // 根节点
private int count=0; //保存节点个数
private int foot = 0;
private Object[] retData;
@SuppressWarnings("rawtypes")
public void add(Object obj) {//数据的追加
Comparable data = (Comparable) obj;
Node newNode = new Node(data);//将数据包装在Node节点中
if(this.root==null) {//保存根节点
this.root = newNode;
}else {
this.root.addNode(newNode);
}
this.count++;
}
public Object[] toArray() {
if(this.count>0) {
this.foot=0;
this.retData = new Object[this.count];
this.root.toArrayNode();
return this.retData;
}else {
return null;
}
}
}
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(new Food("小米",39));
bt.add(new Food("小辣椒",29));
bt.add(new Food("红米",45));
bt.add(new Food("花米",20));
System.out.println(Arrays.toString(bt.toArray()));
}
}