1. 程式人生 > >java 實現二叉樹原理

java 實現二叉樹原理

1.建立二叉樹類,包含節點(主要儲存資料),注意儲存的資料要實現Comparable介面

class BinaryTree {

private Node root;//根節點
private int count;//儲存節點個數
private Object[] reData;//遍歷輸出陣列
private int foot;

private class Node{//節點類
@SuppressWarnings("rawtypes")
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.reData[BinaryTree.this.foot++] =this.data;
if (this.right!=null) {
this.right.toArrayNode();
}
}


}
//***************************新增資料
public void add(Object obj){
Comparable data = (Comparable)obj;
Node newnode = new Node(data);
if (this.root == null) {
this.root = newnode;
}else {
this.root.addNode(newnode);
}
this.count++;
}
//返回資料
public Object [] toArray(){
if (this.count>0) {
this.foot=0;
this.reData = new Object[this.count];
this.root.toArrayNode(); 
return this.reData;
}else {
return null;
}
}
}

2.建立資料

class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age =age;
}
@Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
return this.age-o.age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "姓名:"+this.name+",年齡:"+this.age;
}
}

3.測試

public class TestBinaryTree{
public static void main(String[] args) {
Person p1 = new Person("meimei", 19);
Person p2 = new Person("lisi", 29);
Person p3 = new Person("wangwu", 39);
Person p4 = new Person("zhangliu", 69);
BinaryTree bt = new BinaryTree();
bt.add(p1);
bt.add(p2);
bt.add(p3);
bt.add(p4);
System.out.println(Arrays.toString(bt.toArray()));
}
}

4.結果

[姓名:meimei,年齡:19, 姓名:lisi,年齡:29, 姓名:wangwu,年齡:39, 姓名:zhangliu,年齡:69]