左式堆的簡單實現 C語言描述

2021-07-29 23:29:11 字數 2132 閱讀 1672

左式堆是優先佇列的一種實現,它的目的主要是為了解決二叉堆的合併問題.(你將在後面看到左式堆是如何用遞迴來優美地進行合併的)

零路徑長

把任意節點x的零路徑長(null path length, npl) npl(x) 定義為從x到乙個沒有兩個兒子的節點的最短路徑長。因此,具有0個或1個兒子的節點的npl值為0,而npl(null)=-1。注意,任意節點的零路徑長比它的各個兒子節點的最小值多1。

堆序性質

左式堆的性質是:對於堆中的每乙個節點x,左兒子的零路徑長至少與右兒子的零路徑長一樣大。因此,下圖1中,左邊的二叉樹是左式堆,而右邊的二叉樹則不是。這個性質使左式堆明顯更偏重於使樹向左增加深度,左式堆的名稱也由此而來。

標頭檔案

#ifndef leftheap_leftheap_h

#define leftheap_leftheap_h

struct treenode;

typedef

struct treenode *priorityqueue;

typedef

long

long elementtype;

/* minmal set of priority queue operations */

/* note that nodes will be shared among several */

/* leftlist heaps after a merge; the user must */

/* make sure to not use the old leftist heaps */

priorityqueue initialize(void);

elementtype findmin(priorityqueue h);

int isempty(priorityqueue h);

priorityqueue merge(priorityqueue h1, priorityqueue h2);

#define insert(x, h)(h = insert1((x),h))

priorityqueue insert1(elementtype x, priorityqueue h);

priorityqueue deletemin1(priorityqueue h);

#endif //leftheap_leftheap_h

實現
#include "leftheap.h"

#include

#include

struct treenode ;

int isempty(priorityqueue h)

static

void swapchildren(priorityqueue pnode)

static priorityqueue merge1(priorityqueue h1, priorityqueue h2)

return h1;

}priorityqueue merge(priorityqueue h1, priorityqueue h2)

void fatalerror(char *message)

priorityqueue insert1(elementtype x, priorityqueue h) else

return h;

}void error(char *message)

/* deletemin1 returns the new tree */

/* to get the minmum, use findmin */

/* this is for convenience */

priorityqueue deletemin1(priorityqueue h)

leftheap = h->left;

rightheap = h->right;

free(h);

return merge(leftheap, rightheap);

}elementtype findmin(priorityqueue h)

priorityqueue initialize(void)

可以自行到網上找一些左式堆的加深一下理解

左式堆實現

左式堆是為了方便合併操作實現的。左式堆性質 任意節點x的零路徑長是x到任意沒有兩個兒子的節點的最短路徑。任意乙個節點的零路徑長比他兒子的零路徑長的最大值大1,null的零路徑長是 1 對於x來說,他的左兒子的零路徑長要大於等於右兒子。通過遞迴實現 如下 public class leftisthea...

左式堆的實現與詳解

定義 左式堆 leftist heaps 又稱作最左堆 左傾堆,是計算機語言中較為常用的乙個資料結構。左式堆作為堆的一種,保留了堆的一些屬性。第1,左式堆仍然以二叉樹的形式構建 第2,左式堆的任意結點的值比其子樹任意結點值均小 最小堆的特性 但和一般的二叉堆不同,左式堆不再是一棵完全二叉樹 comp...

左式堆的合併

二叉堆對於合併操作是困難的,因為需要把乙個陣列拷貝到另乙個陣列。左式堆可以高效的地支援合併操作,左式堆與二叉樹之間唯一區別是,左式堆不是平衡的,可能非常趨向不平衡。左式堆的結構 typedef struct treenode leftistheap 任一節點x的零路徑長npl x 定義為從x到乙個沒...