完全二叉樹的應用之堆的實現

2021-09-23 08:19:27 字數 2808 閱讀 5359

今天介紹一種我剛剛學到的新的資料結構.二叉樹 詳情如下:

二叉樹的概念:二叉樹是一種有限節點的集合,也就是說它的節點個數是有限的.

二叉樹的分類:二叉樹分為 完全二叉樹和滿二叉樹

二叉樹的儲存結構:順序儲存結構和鏈式儲存結構

這次主要介紹二叉樹的順序儲存結構 ,順序儲存結構主要介紹完全二叉樹,完全二叉樹是按照一維陣列的形式進行儲存的,因此是非常適合順序儲存這種儲存方式的.而堆是完全二叉樹的乙個具體的應用.

堆又分為:大堆和小堆. 大堆指的是任意雙親節點都大於其左右節點,因此大堆是降序的順序 堆頂元素最大

小堆指的是任意雙親節點都小於其左右節點,因此小堆是公升序的順序 堆頂元素最小

堆的具體實現**如下:

首先第一部分我們來新建乙個原始檔,「heap.h」,在這裡我們定義一下堆的結構,以及關於堆的一系列操作函式

**如下

#pragma once

typedef int hpdatatype;

typedef struct heap heap;

void initheap(heap*hp,hpdatatype*array, int size);

void insertheap(heap*hp, hpdatatype data);

void eraseheap(heap*hp);

int heapsize(heap*hp);

int heapempty(heap*hp);

hpdatatype heaptop(heap*hp);

void destoryheap(heap*hp);

void testheap();

void heapsort(int *array, int size);

第二部分新建乙個標頭檔案:"heap,c"這部分我們來具體實現一下堆的函式操作細節

**如下

if (hp->_size == hp->_capacity)

//拷貝元素

for (int i = 0; i < hp->_size; ++i)

//釋放原空間

free(hp->_array);

//更新引數

hp->_array = ptmp;

hp->_capacity = newcapacity; }

}//初始化堆

void initheap(heap*hp, hpdatatype*array, int size)

hp->_capacity = size;

//將陣列中的元素搬移到堆中

for (int i = 0; i < size; ++i)

hp->_size = size;

// 將該完全二叉樹調整使其滿足堆的性質

//找完全二叉樹中的倒數第乙個非葉子節點

int root = ((size - 2) >> 1);

for (; root >= 0; --root)

}//向堆中插入元素

void insertheap(heap*hp, hpdatatype data)

//刪除堆中元素

void eraseheap(heap*hp)

//先交換 再刪除 再調整

swap(&hp->_array[0], &hp->_array[hp->_size-1]);

hp->_size--;

adjustdown(hp->_array, hp->_size, 0); }

//獲取堆中元素個數

int heapsize(heap*hp)

//檢查堆是否為空

int heapempty(heap*hp)

//獲取堆頂元素

hpdatatype heaptop(heap*hp)

//摧毀堆

void destoryheap(heap*hp)

}//測試堆的相關操作函式

void testheap();

initheap(&hp, array, sizeof(array) / sizeof(array[0]));

printf("%d ", heapsize(&hp));

printf("%d ", heaptop(&hp));

eraseheap(&hp);

printf("%d ", heaptop(&hp));

insertheap(&hp, 0);

printf("%d ", heaptop(&hp));

destoryheap(&hp);

}//調整陣列中元素使其成為堆

void heapadjust(int *array, int size, int parent)

//找到了較大的孩子,然後與雙親比較,

if (array[child]>array[parent])

else }}

//利用刪除堆中元素的思想,對 堆進行排序

void heapsort(int *array, int size)

//2.排序:用堆刪除的思想

int end = size - 1;

while (end)

}//測試堆的排序情況

void testheap();

heapsort( array, sizeof(array) / sizeof(array[0]));

}

第三部分,建立乙個標頭檔案:「test.c」 在此定義函式的入口main函式

**如下:

#include"heap.h" 

#include#includeint main()

二叉堆(完全二叉樹)

最小堆的實現 最小堆是一顆完全二叉樹 這裡用陣列實現完全二叉樹 index 0 1 2 3 4 5 6 value 空 a b c d 任意index,其父親為index 2,左兒子為2 index,右兒子為2 index 1 時間複雜度 o logn include includeusing na...

二叉樹應用 堆

本例中實現了最小堆的構造 插入 刪除。最小堆表示乙個非終端節點均不大於其左右孩子節點。最小堆用完全二叉樹表示,但是二叉樹存入一維陣列中。將完全二叉樹存入陣列,有一些性質。先將二叉樹從上到下,從左到右給每個節點編號0,1.n。那個乙個節點編號i,他的左孩子編號為2 i 1,右孩子編號2 i 2。完全二...

樹 二叉樹 滿二叉樹 完全二叉樹 堆 概念彙總

樹 乙個擁有n 個節點和n 1 條邊的乙個有向無環圖。二叉樹 每個節點最多有兩個子樹的樹結構。滿二叉樹 除最後一層無任何子節點外,每一層上的所有結點都有兩個子結點的二叉樹。完全二叉樹 由滿二叉樹而引出 二叉樹的深度為h,除第 h 層外,其它各層 1 h 1 的結點數都達到最大個數 滿二叉 樹 第 h...