学习二叉树的Java实现,可以先了解链表和Java的对象比较,本例采用实现Comparable接口实现的。
一、实体类
class Book implements Comparable<Book> {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String toString() {
return "书名:" + this.name + ", 价格:" + this.price;
}
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 {
private class Node {
private Comparable data;
private Node left;
private Node right;
public Node(Comparable data) {
this.data = data;
}
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.retArray[foot++] = this.data;
if (this.right != null) {
this.right.toArrayNode();
}
}
}
private Node root;
private int count;
private Object[] retArray;
private int foot;
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);
}
this.count++;
}
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 BinaryTreeDemo {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(new Book("java", 23.93));
bt.add(new Book("oracle", 52.83));
bt.add(new Book("android", 92.01));
bt.add(new Book("mysql", 10.88));
System.out.println(Arrays.toString(bt.toArray()));
}
}