Data Structures (5)

本文详细介绍了如何使用数组、有序数组和完全二叉树实现二叉堆(最小堆和最大堆),包括插入和删除操作的时间复杂度分析。重点讲解了在MinHeap中插入元素的策略,以及堆的调整过程。同时提到了删除操作仅针对最小堆,时间复杂度均为O(logN)。


【二叉堆】
要求:会构建堆 插入 删除; 画图,手动执行中间数据;

Piority Queue(Heap)

Can find the element with the highest \ lowest priority.

InsertionDeletion
ArrayO(1)find:O(n) delete:O(n)
Linked ListO(1)find:O(n) delete:O(n)
Ordered Arrayfind:O(1) insert:O(n)O(1)
Ordered Linked Listfind:O(1) insert:O(n)O(1)

complete binary tree

Its nodes correspond to the nodes numbered from 1 to n in the perfect binary tree of height h.
A complete binary tree of height h has between 2^h and 2^{h+1}-1 nodes.
Array representation: BT[n+1](BT[0]is not used)
For node i:

  • parent: i/2
  • left child: 2*i
  • right child: 2*i+1

A min tree is a tree in which the key value in each node is no larger than the key values in its children.
A min heap :a complete binary tree + a min tree. And the max heap is visa versa.

Insertion(Min Heap)

Because a heap is a complete binary tree, the nth node only has one possible position to insert. Then, if nth node is smaller than its parent:exchange upward will its location is proper.

for ( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 ) 
	H->Elements[ i ] = H->Elements[ i / 2 ]; 

     H->Elements[ i ] = X; 

Another kind of Insertion is: insert all nodes first, then adjust their location. We need to check from n/2 node. If its children node is smaller than it, choose the smallest node and exchange them. n/2 node go downward until reach the proper location. Then do the same thing to the n/2-1 node until the first node.

Deletion

We only need to delete the root node——the smallest node.

  • Exchange the root node with the last node——the nth node.
  • do the same thing mentioned above in the Italic text: re-arrange the new node.
  • Iteratively delete root node until delete the whole heap.
    Those 2 operations’ time complexity are O(log N).

For the perfect binary tree of height h containing 2h+1  1 nodes, the sum of the heights of the nodes is 2h+1 - 1 - (h + 1).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灰海宽松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值