学习二叉树(3) 平衡二叉树 堆 哈夫曼树
设计良好的数据结构可以有效的提高查找效率,降低查找次数
平衡因子 (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个元素按输入顺序存入,满足二叉树结构