二叉樹的性質 百度百科有詳細說明,這裏就不羅嗦了。
二叉樹的順序存儲主要利用數組來實現,在實際存儲中可能存在一定的浪費。當全部只有右子樹的時候,浪費最爲嚴重。
package my.bintree;
public class ArrayBinTree<T> {
private Object[] datas;
private int DEFAULT_DEEP = 8;
// 保存樹的深度,默認爲8
private int deep;
private int arraySize;
public void init() {
this.arraySize = (int) (Math.pow(2, deep) - 1);
this.datas = new Object[this.arraySize];
}
// 默認的深度
public ArrayBinTree() {
this.deep = this.DEFAULT_DEEP;
this.init();
}
// 指定深度
public ArrayBinTree(int deep) {
this.deep = deep;
this.init();
}
// 指定深度和根節點
public ArrayBinTree(int deep, T data) {
this.deep = deep;
this.init();
this.datas[0] = data;
}
/**
* 爲指定節點添加子節點
* @param index 添加子節點的父節點的索引,由於數組從的索引從0開始,索引在計算上有點差別
* @param data 節點數據
* @param left 是否爲左節點
*/
public void add(int index, T data, boolean left) {
if (this.datas[index] == null) {
throw new RuntimeException(index + "節點爲空");
}
if (2 * index + 1 >= this.arraySize) {
throw new RuntimeException("樹底層已滿");
}
if (left) {
this.datas[2 * index + 1] = data;
} else {
this.datas[2 * index + 2] = data;
}
}
public boolean empty(){
return this.datas[0] == null;
}
@SuppressWarnings("unchecked")
public T getRoot(){
if(this.empty()){
return (T)this.datas[0];
}
return null;
}
@SuppressWarnings("unchecked")
public T getParent(int index){
if(index >=0 && index < this.arraySize){
return (T)this.datas[index/2 -1];
}
return null;
}
@SuppressWarnings("unchecked")
public T getLeft(int index){
if(2*index + 1 >= this.arraySize){
throw new RuntimeException("該節點爲葉子節點,無子節點");
}
return (T)this.datas[2*index+1];
}
@SuppressWarnings("unchecked")
public T getRight(int index){
if(2*index + 2 >= this.arraySize){
throw new RuntimeException("該節點爲葉子節點,無子節點");
}
return (T)this.datas[2*index+2];
}
public int deep(){
return this.deep;
}
//獲取指定節點的位置
public int position(T data){
for(int i=0;i<this.arraySize;i++){
if(this.datas[i].equals(data)){
return i;
}
}
return -1;
}
@Override
public String toString(){
return java.util.Arrays.toString(this.datas);
}
}
最後使用一個測試Client來測試下基本功能是否已經實現:
package my.bintree;
public class ArrayBinTreeClient {
public static void main(String[] args) {
ArrayBinTree<String> tree = new ArrayBinTree<String>(4, "root");
tree.add(0, "0_left", true);
tree.add(0, "0_right", false);
tree.add(1, "1_left", true);
tree.add(1, "1_right", false);
tree.add(2, "2_left", true);
tree.add(2, "2_right", false);
System.out.println(tree);
}
}
控制檯輸出:
[root, 0_left, 0_right, 1_left, 1_right, 2_left, 2_right, null, null, null, null, null, null, null, null]