数据结构中最欣欣向荣的两个分支就是:平衡树 和可合并堆,高级树结构的核心都是围绕如何使树到达平衡而展开,高级堆结构的核心就是如何有效地进行合并。左式堆由于使用二叉链表的存储结构,对动态操作支持良好,在需要合并操作的场合,是极佳的选择。
左式堆的性质:
1.【堆性质】:任意节点的关键字大于等于其孩子节点的关键字,为了让最小的结点始终在根的位置。
2.【左偏性质】:定义到最近的孩子的距离为节点距离dist,那么任意节点的左孩子的距离大于右孩子的距离,为了让树状存储的堆,树的深度不能过大,且利于合并,并且插入的时候总从较短的右子树插入。
A->lchild->dist >= A->rchild->dist
// zuoshidui.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#includeusing namespace std;#ifndef _LefeHeap_Hstruct TreeNode;typedef struct TreeNode *PriorityQueue;PriorityQueue Initialize(void);int FindMin(PriorityQueue H);bool isEmpty(PriorityQueue H);PriorityQueue Merge(PriorityQueue H1, PriorityQueue H2);#define Insert(x,H) (H=Insert1((x),H))PriorityQueue Insert1(int x, PriorityQueue H);PriorityQueue DeleteMin1(PriorityQueue H);#endif // !_LefeHeap_Hstruct TreeNode{ int element; PriorityQueue Left; PriorityQueue Right; int Npl;};void SwapChildren(PriorityQueue& H){ PriorityQueue temp = H->Left; H->Left = H->Right; H->Right = temp;}static PriorityQueue Merge1(PriorityQueue H1, PriorityQueue H2){ if (H1->Left == NULL) H1->Left = H2; else { H1->Right = Merge(H1->Right, H2); if (H1->Left->Npl < H1->Right->Npl) SwapChildren(H1); H1->Npl = H1->Right->Npl + 1; } return H1;}PriorityQueue Merge(PriorityQueue H1, PriorityQueue H2) //默认堆头较小的元素作为Merge1的第一个参数{ if (H1 == NULL) return H2; if (H2 == NULL) return H1; if (H1->element < H2->element) return Merge1(H1, H2); else return Merge1(H2, H1);}PriorityQueue Insert1(int x, PriorityQueue H) //把插入操作视为一个单节点和一个左式堆合并{ PriorityQueue SingleNode; SingleNode = (PriorityQueue)malloc(sizeof(TreeNode)); if (SingleNode == NULL) cout << "out of space"; else { SingleNode->element = x; SingleNode->Npl = 0; SingleNode->Left = SingleNode->Right = NULL; H = Merge(SingleNode, H); } return H;}bool isEmpty(PriorityQueue H){ if (H == NULL) return true; else return false;}PriorityQueue DeleteMin1(PriorityQueue H){ PriorityQueue LeftHeap, RightHeap; if (isEmpty(H)) { cout << "Priority queue is empty"; return H; } LeftHeap = H->Left; RightHeap = H->Right; free(H); return Merge(LeftHeap, RightHeap);}int main(){ return 0;}