開發者學堂課程【Java 進階程式設計:二叉樹基礎實作】學習筆記,與課程緊密聯系,讓使用者快速學習知識。
課程位址:
https://developer.aliyun.com/learning/course/20/detail/364二叉樹基礎實作
内容介紹:
1. person 類
2. comparable 使用範例
在實作二叉樹的處理之中最為關鍵性的問題在于資料的儲存,而且資料由于牽扯到對象比較的問題,那麼一定要有比較器的支援,而這個比較器首選的一定就是Comparable,是以本次将儲存一個 Person 類資料
person 類:
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 com pareTo(Person per) {
return this age-per. age;
}
//無參構造、setter、getter略
@override
public string tostring() {return“ 【Person類對象】姓名:”+this.name+“、年齡.”+this. age+“\n”;}
}
随後如果要想進行資料的儲存,首先一定需要有一個節點類。節點類裡面由于牽扯是以必須使用 comparable(可以區分大小);
package cn. midn. demo;
public class JavaAPIDemo {
public static void main(String[] args) {
BinaryTree<Person> tree = new BinaryTree<Person>();
tree. add(new Person(“小強-80”,80));
tree. add(new Person(“小強-30”,30));
tree. add(new Person(“小強-50”,50));
tree. add(new Person(“小強-60”,60));
tree. add(new Person("小強-90",90));
System. out. println(Arrass. to String(tree. to Array());
}
}
/**
* 實作二叉樹操作
* @param<T> 要進行二叉樹的實作
*
*/
class BinaryTree<T extends Comparable<T>> {
private class Node{
private Comparable<T>data;//存放Comparable.可以比較大小
private Node parent;_//儲存父節點
private Node left;//儲存左子樹
private Node right;//儲存右子樹
public Node(Comparable<T> data) {(//構造方法直接負責進行資料的存儲
this.data=data;
}
/**
* 實作節點資料的适當位置的存儲
* @param newNode 建立的新節點
public void addNode(Node newNode) {
if (newNode.data.compareTo((T)this.data) <=0) {
if (this.left == null) { //現在沒有左子樹
this.left = newNode; //儲存左子樹
newNode.parent = this;//儲存父節點
} else { //需要向左邊繼續判斷
this.left.addNode(newNode); //繼續向下判斷
}
} else { //比根節點的資料要大
if (this.right == null) {
this.right = newNode ;//沒有右子樹
newNode.parent = this ;//儲存父節點}
} else {
this.right.addNode(newNode); //繼續向下判斷
}
}
} /*
*實作所有資料的擷取處理,按照中序周遊的形式來完成
*/
public void to ArrayNode() {
if(this. Left ! = null) { //有左子樹
this. left.toArrayNode();//遞歸調用
}
BinaryTree. this.returnData[BinaryTree. this.foot ++] = this.data
if(this. right's null){
this. right.toArrayNode();
}
}
}
//----------以下為二叉樹的功能實作------------
private Node root ; //儲存的是根節點
private int count;//儲存資料個數
private Object [] retuenData;//傳回的資料
private int foot = 0;//腳标控制
/**
* 進行資料的儲存
* @param data 要儲存的資料内容
* @exception NullPointerException 儲存資料為空時抛出的異常
*/
public void add(Comparable<T> data ) {
if (data == null) {
throw new NullPointerException(“儲存的資料不允許為空!”);
}
// 所有的資料本身不具備有節點關系的比對,那麼一定要将其包裝在 Node 類之中
Node newNode = new Node(data);//
儲存根節點
if(this.root == null)
{//現在沒有根節點,則第一個節點作為根節點
this.root = newNode ;
} else {
//需要為其儲存到一個合适的節點
This.root.addNode(newNode);//交友Node類負責處理
}
This.count++;
}
*以對象數組的形式傳回全部資料,如果沒有資料傳回null
*@return全部資料
public Object[] toArray() {
if(this. count==0){
return null;
}
This.returnData = new Object[this.count];//儲存長度為組長長度
this. foot=0;//腳标清零
this. root.toArrayNode();//直接通過Node類負責
return this.returnDataj//傳回全部的資料
}
}
在進行資料添加的時候隻是實作了節點關系的儲存,而這種關系儲存後的結果就是所有資料都屬于有序排列。