数据结构 — BinaryTree
二叉树
树一种比链表更为复杂的概念,本质也属于动态对象数组,但是与链表不同
在于,树的最大特征是可以针对于数据进行排序
树的操作原理,选中第一个数据作为根节点,而后比根节点小的放在根节点的
左子树,比根节点大的放在右子树,取得的时候按照中序遍历的方式取出 左 中 右
package leiku;
import java.lang.reflect.Array;
import java.util.Arrays;
class Book13 implements Comparable<Book13> ///实现比较
{
private String title;
private double price;
public Book13(String title,double price)
{
this.title = title;
this.price = price;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "书名"+this.title+"价格"+this.price+"\n";
}
@Override
public int compareTo(Book13 o) { //Arrays。sort() 会自动跳动此方法比较
// TODO Auto-generated method stub
if(this.price>o.price)
{
return -1;
}
else if(this.price<o.price)
{
return 1;
}
else
{
return 0;
}
}
}
@SuppressWarnings("rawtypes")
class BinaryTree
{
private class Node
{
private Comparable data; 排序的依据就是Comparable
private Node left; ///保存左节点
private Node right; /// 保存有节点
@SuppressWarnings("unused")
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);
}
}
}
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 int count;
private Object [] retData;
private int foot;
public void add(Object obj) /// 进行数据的追加
{
Comparable com = (Comparable)obj; /// 必须变为Comparable 才可以实现Node保存
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;
}
}
public class ercashu {
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTree bt = new BinaryTree();
bt.add(new Book13("adasd", 11412));
bt.add(new Book13("adadasasd", 1132));
bt.add(new Book13("adadassd", 12123));
bt.add(new Book13("adaadassd", 1122));
Object obj [] =bt.toArray();
System.out.println(Arrays.toString(obj));
}
}