1.什麼是樹
圖解(靈魂畫師)
2.樹的相關知識
3.樹的實現
樹的實現主要有三個:
1.父節點表示法:該方法主要思路是,每個節點存儲父節點的位置,這樣就構成一棵樹
2.孩子鏈表示法:該方法的主要思路是,每個節點用數組存儲孩子位置,不過這個表示法有個致命的缺陷,就是造成大量空間上的浪費,因爲數組最大的長度必定和最多的度相等,但是並不是每個子樹都有那麼多度,所以造成空間上的浪費;
3.兄弟孩子節點表示法:該方法主要思路是:每個節點存儲孩子,兄弟節點位置,本次就用這個表示法實現
下面代碼只實現了添加功能,有空再補上其他功能,其他功能也是大同小異,至於爲什麼有個flag變量,因爲我覺得樹裏存在重複的變量,所以用flag來唯一標識一個樹
package Tree;
/*
* 樹的整體
* @author WLNSSS
* @time 2017.12.22
* */
public class MyTree<T> {
// 記錄根樹
private Node root;
// 記錄節點數
private int nodeCount;
// 記錄節點標識的位置
private int superFlag;
public MyTree(T data) {
//初始化,構造器先裝配一個根節點
root = new Node(data);
}
// 在指定位置添加節點
public void add(T data, int flag) {
// 定位到指定的位置
Node point = getNodePost(flag);
// 錯誤檢查,判斷是否是空,如果空拋出異常
if (point == null) {
throw new NullPointerException("沒有此元素");
} else {
// 判斷孩子節點空或非空,然後進行不同的操作
if (point.getChlid() == null) {
point.setChlid(new Node(data));
}
if (point.getChlid() != null) {
Node temp = point.getChlid();
Node newNode = new Node(data);
newNode.setBrother(temp);
point.setChlid(newNode);
}
// 元素標識+1
flag++;
}
}
// 定位節點位置,找出該節點
public Node getNodePost(int flag) {
// 調用另外一個複用方法實現
return getNodePost(flag, root);
}
// 定位節點位置,找出該節點
private Node getNodePost(int flag, Node ponit) {
// 節點指針,先從root節點開始遞歸
Node point = root;
// 當遞歸到一個元素的flag等於要查找的flag則返回當前的指針
if (point.flag == flag) {
return point;
}
// 若兄弟節點非空,則遞歸取出元素
if (point.getBrother() != null) {
return getNodePost(flag, point.getBrother());
}
// 若子節點非空,則遞歸取出元素
if (point.getChlid() != null) {
return getNodePost(flag, ponit.getChlid());
}
// 若沒找到則返回null
return null;
}
/*
* 樹的節點(內部類)
*/
private class Node {
// 存儲的數據
T data;
// 子節點位置
Node chlid;
// 兄弟節點位置
Node brother;
// 唯一標識該節點的變量
int flag;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getChlid() {
return chlid;
}
public void setChlid(Node chlid) {
this.chlid = chlid;
}
public Node getBrother() {
return brother;
}
public void setBrother(Node brother) {
this.brother = brother;
}
public Node(T data) {
this(data, null, null,superFlag);
}
public Node(T data, Node chlid, Node brother,int flag) {
this.data = data;
this.chlid = chlid;
this.brother = brother;
this.flag = flag;
}
}
public static void main(String[] args) {
MyTree<Integer> myTree = new MyTree(12);
myTree.add(1,0);
myTree.add(2,0);
System.out.println(myTree.root.chlid.brother.getData());
}
}