Docsity

Heaps and Priority Queues - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Heaps and Priority Queues - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Chapter 9

Heaps and Priority Queues

Lecture 18

Full Binary Tree

  • Every non-leaf node has two children
  • Leaves are on the same level

Full Binary Tree

Examples of Different Types of Binary Trees 4

What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties:

  • Its shape must be a complete binary tree.
  • For each node in the heap, the value stored in that node is greater than or equal to the value in each of its children.

Is this a Heap?

tree

Not unique!

We Can Number the Nodes Left to Right by Level This Way

tree

And use the Numbers as Array Indexes to Store the Trees 70 0 60 1 40 3 30 4 12 2 8 5 tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] 70 60 12 40 30 8 tree.nodes

// HEAP SPECIFICATION // Assumes ItemType is either a built-in simple data // type or a class with overloaded relational operators. template< class ItemType > struct HeapType { void ReheapDown ( int root , int bottom ) ; void ReheapUp ( int root, int bottom ) ; ItemType* elements; //ARRAY to be allocated dynamically int numElements ; };

ReheapDown

bottom

ReheapDown (cont)

if ( leftChild <= bottom ) // ReheapDown continued

if ( leftChild == bottom )

maxChild = leftChld;

else

if (elements [ leftChild ] <= elements [ rightChild ] )

maxChild = rightChild;

else

maxChild = leftChild;

if ( elements [ root ] < elements [ maxChild ] )

Swap ( elements [ root ] , elements [ maxChild ] );

ReheapDown ( maxChild, bottom ) ;

O(logN)

ReheapUp

bottom

Real-life Priority Queue