二叉堆的實現

2021-09-01 09:57:13 字數 1577 閱讀 1727

1.堆的概念

這裡只需要注意兩點:

a.堆的儲存方式:就是順序儲存在陣列中,在二叉樹中表現為滿二叉樹

b.堆的用處:用於排序,查詢最大最小都非常方便

2.堆的實現

heapexception.h

#ifndef heapexception_h

#define heapexception_h

class arrayoverflowexception

};class parameterserrorexception

};class underflowexception

};#endif

heap.h

//二叉堆,是一顆被完全填滿的二叉樹,完全二叉樹,故而可以使用順序儲存在陣列中

#ifndef heap_h

#define heap_h

templateclass binaryheap;

#endif

heap.cpp

#include #include "heap.h"

#include "heapexception.h"

using namespace std;

templatebinaryheap::binaryheap()

templatebinaryheap::binaryheap( const t* items, const int size)

templatebool binaryheap::isempty() const

templateconst t& binaryheap::findmin() const

templatevoid binaryheap::insert( const t x)

//在最後建立乙個空的位置,如果滿足條件則上浮

int hole = ++currentsize;

for(; hole>1 && x < array[hole/2]; hole/=2)

array[hole] = x; }

templatevoid binaryheap::deletemin()

templatevoid binaryheap::deletemin( t& minitem)

templatevoid binaryheap::makeempty()

templatevoid binaryheap::buildheap()

}//將結點下濾,即從頂至葉子的調整過程(小根堆)

templatevoid binaryheap::percolatedown(int hole)

//如果當前比hole小,交換

if(array[child]void binaryheap::resize(int capacity);

trycatch(arrayoverflowexception e)catch(parameterserrorexception e)catch(underflowexception e)

return 0;

}

二叉堆的實現

include include define max heap size 101 class binaryminheap void insert intvalue void removemin intgetmin void displayheaparray private int heaparray...

二叉堆的實現

二叉堆是一種特殊的堆,二叉堆是完全二元樹 二叉樹 或者是近似完全二元樹 二叉樹 二叉堆有兩種 最大堆和最小堆。最大堆 父結點的鍵值總是大於或等於任何乙個子結點的鍵值 最小堆 父結點的鍵值總是小於或等於任何乙個子節點的鍵值。二叉堆一般都通過 陣列 來實現。陣列實現的二叉堆,父節點和子節點的位置存在一定...

二叉堆實現二

堆可以視為一棵完全二叉樹,樹的每一層都是被填滿的,最後一層可能除外,所以堆可以用陣列來表示。對於陣列中任意位置 i上的元素,其左兒子在位置 i 2 1 其右兒子在位置 i 2 2 上,其父節點在位置 i 1 2 1處。二叉堆有兩種 最大堆和最小堆。最大堆中,除根結點外 其無父結點 每個結點的關鍵字都...