最大堆和最小堆和平衡二叉树_最小堆二叉树

本文介绍了最小堆二叉树的概念,包括其性质和数组表示方式。讲解了如何在C语言中实现最小堆,包括插入元素和从堆中删除元素的操作,以及heapify()过程确保最小堆属性。文章提供了完整的代码示例,并讨论了实现的时间复杂度。
摘要由CSDN通过智能技术生成

最大堆和最小堆和平衡二叉树

A Min Heap Binary Tree is a Binary Tree where the root node has the minimum key in the tree.

最小堆二叉树是二叉树,其中根节点在树中具有最小密钥。

The above definition holds true for all sub-trees in the tree. This is called the Min Heap property.

上面的定义对于树中的所有子树都适用。 这称为“ 最小堆”属性。

Almost every node other than the last two layers must have two children. That is, this is almost a complete binary tree, with the exception of the last 2 layers.

除了最后两层以外,几乎每个节点都必须有两个子节点。 也就是说,除了最后两层外,这几乎是完整的二叉树。

The below tree is an example of a min heap binary tree since the above two properties hold.

由于上面的两个属性成立,因此下面的树是最小堆二叉树的示例。

Min Heap Btree
Min Heap Btree
最小堆树

Now that we’ve covered what a min heap tree is, let’s look at how we can represent it.

现在我们已经了解了最小堆树是什么,让我们看看如何表示它。



最小堆树的表示 (Representation of a Min Heap Tree)

A Min Heap Binary Tree is commonly represented as an array, which is indexed according to the below format:

最小堆二叉树通常表示为数组,并根据以下格式进行索引:

Current Node arr[i]
Parent Node arr[(i-1)/2]
Left Child arr[(2*i) + 1]
Right Child arr[(2*i )+ 2]
当前节点 arr[i]
父节点 arr[(i-1)/2]
左子 arr[(2*i) + 1]
合适的孩子 arr[(2*i )+ 2]

The root of the whole tree is at arr[0].

整个树的根位于arr[0]

We will use the indexing as shown in the below figure. It’s not very hard to find the pattern here, which will match with the above table.

我们将使用下图所示的索引。 在此处找到与上表匹配的模式不是很困难。

Min Heap Binary Tree Index
Min Heap Binary Tree Index
最小堆二叉树索引

This indexing follows a Level Order Traversal of the Binary Tree, so a Binary Heap array is a Binary Tree using a level order traversal.

该索引遵循二进制树的级别顺序遍历 ,因此,二进制堆数组是使用级别顺序遍历的二进制树。

Min Heap Array
Min Heap Array
最小堆数组

The above figure shows the array representation of the Min Heap Tree.

上图显示了最小堆树的数组表示形式。

Now that we’ve covered the concepts, let’s move onto implementing this in C!

现在我们已经涵盖了概念,让我们继续使用C来实现它!



实施最小堆树 (Implementing a Min Heap Tree)

We will use the array representation to build the tree. Let’s start writing the structure for the Min Heap.

我们将使用数组表示法来构建树。 让我们开始编写Min Heap的结构。


typedef struct MinHeap MinHeap;
struct MinHeap {
    int* arr;
    // Current Size of the Heap
    int size;
    // Maximum capacity of the heap
    int capacity;
};

We’ll have an array of elements, and a size, which gets updated as elements are being inserted or deleted.

我们将有一个元素数组和一个大小,该大小会随着元素的插入或删除而更新。

The array also has a capacity, which indicates the maximum size of the array.

阵列还具有容量,该容量指示阵列的最大大小。

There are a few functions that we need to write to indicate that we are representing a Min Heap Tree, like finding the parent, and the children.

我们需要编写一些函数来表示我们正在代表最小堆树,例如查找父级和子级。


int parent(in
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值