java 二叉排序_二叉排序树之Java实现

二叉排序树查找

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));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值