二叉排序树查找
import java.util.Arrays;
class BinaryTree{
private class Node{
@SuppressWarnings("rawtypes")
private Comparable data;
private Node left;
private Node right;
public Node(@SuppressWarnings("rawtypes") 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();
}
}
}
private Node root;
private int count;
private Object[] retData;
private int foot;//定义角标
@SuppressWarnings("rawtypes")
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);
}
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;
}
}
class Book implements Comparable
{
private String name;
private double price;
public Book(String name,double price)
{
this.name=name;
this.price=price;
}
public int compareTo(Book book)//Arrays.sort()会自动调用此方法
{
if(this.price>book.price)
return 1;
else if(this.price==book.price)
return 0;
else
return -1;
}
public String toString(){
return "书名: "+this.name+",价格: "+this.price+"\n";
}
}
public class sortedTree {
public static void main(String[] args){
BinaryTree bt=new BinaryTree();
bt.add(new Book("Java开发",79.8));
bt.add(new Book("Jsp开发",69.7));
bt.add(new Book("Oracle开发",99.8));
bt.add(new Book("Android开发",89.7));
Object obj[]=bt.toArray();
System.out.println(Arrays.toString(obj));
}
}