Java比较器(Comparable二叉树的实现)

范例:

import java.util.Arrays;

class Book implements Comparable<Book> {
	private String title;
	private double price;

	public Book(String title, double price) {
		this.title = title;
		this.price = price;
	}

	@Override
	public String toString() {
		return "书名:《" + this.title + "》,价格:" + this.price + "元。";
	}

	@Override
	public int compareTo(Book o) {
		if (this.price > o.price) {
			return 1;
		} else if (this.price < o.price) {
			return -1;
		} else {
			return 0;
		}
	}
}

class BinaryTree {
	class Node {
		@SuppressWarnings("rawtypes")
		private Comparable data;// 排序的依据是Comparable
		private Node left;// 左节点
		private Node right;// 右节点

		@SuppressWarnings("rawtypes")
		public Node(Comparable data) {
			this.data = data;
		}

		// 1.添加节点
		@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);
				}
			}
		}

		// 2.对象数组
		public void toArrayNode() {
			if (this.left != null) {
				this.left.toArrayNode();
			}
			BinaryTree.this.retArray[BinaryTree.this.foot++] = this.data;
			if (this.right != null) {
				this.right.toArrayNode();
			}
		}
	}

	// =================以上是内部类==================
	private Node root;// 根节点
	private int count;// 保存元素个数
	private int foot;// 脚标
	private Object[] retArray;// 对象数组

	// 1.添加对象
	@SuppressWarnings("rawtypes")
	public void add(Object obj) {
		if (obj == null) {
			return;
		}
		Comparable com = (Comparable) obj;
		Node newNode = new Node(com);
		if (this.root == null) {
			this.root = newNode;
		} else {
			this.root.addNode(newNode);
		}
		this.count++;
	}

	// 2.对象数组
	public Object[] toArray() {
		if (this.root == null) {
			return null;
		}
		this.foot = 0;
		this.retArray = new Object[this.count];
		this.root.toArrayNode();
		return this.retArray;
	}
}

public class Demo {
	public static void main(String[] args) {
		BinaryTree bt = new BinaryTree();
		bt.add(new Book("Java从入门到精通", 88.6));
		bt.add(new Book("Oracle从入门到精通", 99.6));
		bt.add(new Book("Android开发", 88.5));
		Object[] data = bt.toArray();
		System.out.println(Arrays.toString(data));
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值