package cn.mdln.program;
import java.util.Arrays;
import java.util.Arrays;
/**
* 树:(有向图)连通的,无回路,有向图
* 树最基本的:是二叉树
* 由小到大输出:中序遍历(左-中-右)
* @author Administrator
*
*/
public class MyBinaryTree {
public static void main(String[] args) {
BinaryTree bt=new BinaryTree();
bt.add(new Bookb("java讲义",79.8));
bt.add(new Bookb("jsp开发",75.8));
bt.add(new Bookb("Spring框架",67.8));
bt.add(new Bookb("Structs2框架",72.8));
bt.add(new Bookb("hibemate框架",63.8));
System.out.println("\t"+"\t二叉树转化为对象数组遍历---");
Object []obj=bt.toArray();
for(int i=0;i<obj.length;i++)
{
Bookb b=(Bookb)obj[i];
System.out.println(b.getInfo());
}
System.out.println("\t"+"\t二叉树中序遍历---");
bt.print();//遍历
}
}
class Bookb implements Comparable<Bookb>{ //排序必须实现Comparable接口
private String title;
private double price;
public Bookb(String title,double price)
{
this.title=title;
this.price=price;
}
public String getInfo()
{
return "\t图书名称:"+this.title+",价格:"+this.price;
}
public String tostring()
{
return "\t图书名称:"+this.title+",价格:"+this.price;
}
public int compareTo(Bookb book)
{
if(this.price>book.price)
return 1;
else if(this.price<book.price)
return -1;
else
return this.title.compareTo(book.title);
}
}
class BinaryTree{
private Node root;//根节点来控制整个二叉树
private int count=0;//统计节点个数
private int foot;//自增器,用来控制角标
private Object[] toarray;//将链表转化为对象数组输出
private class Node
{
private Comparable data;//排序依靠的是Comparable接口
private Node left;
private Node right;
public Node(Comparable data)
{
this.data=data;
}
public void addNode(Node node)
{
if(this.data.compareTo(node.data)>0)
{
if(this.left==null)
this.left=node;
else
this.left.addNode(node);
}
else
{
if(this.right==null)
this.right=node;
else
this.right.addNode(node);
}
}
public void toArrayNode()
{
if(this.left!=null)
this.left.toArrayNode();
BinaryTree.this.toarray[ BinaryTree.this.foot++]=this.data;
if(this.right!=null)
this.right.toArrayNode();
}
public void printNode()
{
if(this.left!=null)
this.left.printNode();
Bookb a=(Bookb)this.data;
System.out.println(a.getInfo());
if(this.right!=null)
this.right.printNode();
}
}
public void add(Object obj)
{
Comparable com=(Comparable)obj;//必须强制转型(向下转型)为才可以保存Node类
Node newNode=new Node(com);//创建一个新节点
if(BinaryTree.this.root==null)
{
this.root=newNode;
}
else
{
this.root.addNode(newNode);//交给Node类处理
}
this.count++;
}
public Object[] toArray()
{
if(this.root==null)
return null;
this.foot=0;
this.toarray=new Object[this.count];
this.root.toArrayNode();
return this.toarray;
}
public void print()
{
if(this.root.left!=null)
this.root.left.printNode();
Bookb b=(Bookb)this.root.data;
System.out.println(b.getInfo());
if(this.root.right!=null)
this.root.right.printNode();
//Bookb b=(Bookb)BinaryTree.this.data;
// System.out.println(b.getInfo());
}
}