package BinaryTree;
/**
* 选择第一个元素作为根节点
* 比根节点打的数据保存在右子数
* 比根节点数据小的保存在左子树
* 输出:中序遍历
* 左→中→右
* @author LY
*
*/
public class TestBinaryTree {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(new Phone("和米",103.10));
bt.add(new Phone("白米",122.10));
bt.add(new Phone("绿米",103341.10));
System.out.println(bt.size());
Object result[] = bt.toArray();
for (Object object : result) {
System.out.println(object);
}
}
}
package BinaryTree;
//二叉树实现类
public class BinaryTree {
//首先要定义一个Node的类来进行节点的处理操作
private class Node{
private Comparable data;
private Node left; //比根节点打的数据保存在右子数
private Node right; //比根节点数据小的保存在左子树
Node(Comparable data){ //编写Node的构造函数
this.data = data;
}
public void addNode(Node newNode) {
if(newNode.data.compareTo(this.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);
}
}
}
private void toArrayNode() {
if(this.left != null){
this.left.toArrayNode();
}
BinaryTree.this.retObj[BinaryTree.this.foot++] = this.data;
if(this.right!= null){
this.right.toArrayNode();
}
}
}
//*****************************************
//编写BinaryTree的程序
private Node root; //任何节点操作都离不开根节点
private int count; //进行数据统计
private int foot; //进行标记
private Object[] retObj; //创建数组用来接收保存的数据
public void add(Object obj){
Node newNode = new Node((Comparable)obj);
if(obj == null){
return ;
}
if(this.root == null){
this.root = newNode;
}else{
this.root.addNode(newNode);
}this.count++;
}
public int size(){
return this.count;
}
public Object[] toArray(){
this.foot = 0;
if(this.count == 0){
return null;
}
this.retObj = new Object[this.count];
this.root.toArrayNode();
return this.retObj;
}
}
package BinaryTree;
public class Phone implements Comparable<Phone>{
private String brand;
private double price;
@Override
public String toString() {
return "Phone [brand=" + brand + ", price=" + price + "]";
}
public Phone(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public int compareTo(Phone o) { //实现二叉树得进行对象比较,然而想对电话这样的类进行比较就需要实现Comparable的接口,覆写compareTo方法来对电话里的price属性进行比较
if(this.price > o.price){
return 1;
}if(this.price < o.price){
return -1;
}return 0;
}
}
简单BinaryTree实现
最新推荐文章于 2018-03-25 17:41:26 发布