設計良好的數據結構可以有效的提高查找效率,降低查找次數
平衡因子 (Balance Factor,Bf) BF(T)=hl-hr; hl,hr分別爲左右子樹的高度
平衡二叉查找樹(Balance Binary Tree) (AVL樹) |BF|<=1
設nh高度爲h的平衡二叉樹的最少結點數。節點數最少時 nh=nh-1+nh-2+1 斐波那契數列
nh=Fh+2-1 Fh 斐波那契數列
給定結點數爲 n的AVL樹的
最大高度爲O(log2n)!
堆
優先隊列:特殊的隊列,取出元素的順序是依照元素的優先權大小,而不是元素進入隊列的先後順序
兩個特性:1.結構性:用數組表示的完全二叉樹
2.有序性:任意結點的關鍵字是其子樹所有節點的最大值或最小值
最大堆:也稱大頂堆 最大值 任何結點都是所在子樹的最大值
最小堆:也稱小頂堆 最小值 任何結點都是所在子樹的最小值
* :從根節點到任意結點路徑上結點序列的有序性
public class MaxHeap {
public int[] element; // 存儲堆元素的數組
public int size; //堆當前元素的個數
public int capacity; //堆的最大容量
public MaxHeap(int[] element, int size, int capacity) {
this.element = element;
this.size = size;
this.capacity = capacity;
}
public MaxHeap() {
}
public MaxHeap createMaxHeapTypeIsInt(int maxSize){
int MaxData=9999999;
MaxHeap heap=new MaxHeap();
heap.element=new int[1+maxSize];
heap.size=0;
heap.capacity=maxSize;
heap.element[0]=MaxData; //定義哨兵爲大於堆中所有可能元素的值,便於以後更快操作
return heap;
}
//最大堆插入
public void insert(MaxHeap heap,int item){
//將元素item 插入最大堆heap中,其中heap.elements[0] 已經定義爲哨兵
int i;
if (heap.size==heap.capacity){
System.out.println("最大堆已滿");
return;
}
i=++heap.size; // i指向插入後堆中的最後一個元素的位置
for ( ; heap.element[i/2] <item ; i/=2) {
heap.element[i]=heap.element[i/2]; //向下過濾結點
}
heap.element[i]=item; //將item 插入
}
//最大堆刪除
// 取出根結點元素,同時刪除堆的一個結點
public Integer delete(MaxHeap heap){
int parent,child;
int MaxItem,temp;
if (heap.size==0){
System.out.println("最大堆爲空");
return null; }
MaxItem=heap.element[1]; //取出根節點最大值
temp=heap.element[heap.size--];
// 用最大堆中最後一個元素從根節點開始向下過濾下層結點
for (parent=1;parent*2<=heap.size;parent=child){ //parent*2<=heap.size判別是否擁有左兒子 左兒子2*root.index 右兒子2*+1
child=2*parent;
if ((child!=heap.size)&&(heap.element[child]<heap.element[child+1]))
child++; // child 指向左右子節點的較大者
if (temp>=heap.element[child]) break;
else heap.element[parent]=heap.element[child];//移動temp到下一層
}
heap.element[parent]=temp;
return MaxItem;
}
//最大堆的建立1.通過插入操作 nlohn 2.線性時間複雜度下建立最大堆 將n個元素按輸入順序存入,滿足二叉樹結構