树的操作原理:
选择第一个数据作为根节点,而后比根节点小的放在根节点的左子树(左节点),
比根节点大的放在根节点的右子树(右节点),取得的时候按照中序遍历的方式取出(左-中-右)
import java.util.Arrays;
public class test{
public static void main(String args[]){
Book[] books = new Book[]{
new Book("java",34.5),
new Book("c++",34.5),
new Book("c",40.5)
};
BinaryTree bt = new BinaryTree();
bt.add(new Book("java",34.5));
bt.add(new Book("java",37));
bt.add(new Book("java",35));
bt.add(new Book("java",50));
Object obj[] = bt.toArray();
for(Object b : obj){
System.out.println(b);
}
}
}
class Book implements Comparable<Book> {
private String title;
private double price;
Book(String title,double price){
this.title = title;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", price=" + price +
'}';
}
@Override
public int compareTo(Book o) {
if(this.price>o.price){
return 1;
}else if(this.price < o.price){
return -1;
}else {
return 0;
}
}
}
class BinaryTree{
private class Node{
private Comparable data; //排序的依据就是Comparable
private Node left; //保存左节点
private Node right;//保存右节点
private int count=0; //保存元素个数
public Node(Comparable data){
this.data = data;
}
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);
}
}
this.count++ ;
}
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();
}
}
}
private Node root; //定义根节点
private Object[] retData;
private int foot=0;
private int count=0;//保存元素个数
public void add(Object obj) { //进行数据的追加
Comparable com = (Comparable)obj;
Node newNode = new Node(com);
if(this.root == null){
this.root = newNode;
}else{
this.root.addNode(newNode);
}
this.count++;
}
public Object[] toArray(){
if(this.root == null){
return null;
}
this.foot = 0;
this.retData = new Object[this.count];
this.root.toArrayNode();
return this.retData;
}
}