Educational_Resources

Lecture 4: Binary Heaps & Graphs

Created By: Yusuf Pisan

formatted to Github Markdown syntax by Ryan Peters

Be sure to check the other lectures out after you finish this one!

Previous lecture Next lecture

Table of Contents


Overview


const

https://isocpp.org/wiki/faq/const-correctness


Runtime polymorphism - virtual + override

http://www.cplusplus.com/doc/tutorial/polymorphism/


Decision Trees


Heap

MaxHeap: Complete binary tree whose root is greater than its children

MinHeap: …

Not a binary search tree!


Heap - Array Based Implementation

Keep track of itemcount and maxItems


Heap - Array into a Heap

void heapRebuild(const int subTreeNodeIndex)
{
   if (!isLeaf(subTreeNodeIndex))
   {
      // Find larger child
      int leftChildIndex = ...
      int rightChildIndex = ...
      int largerChildIndex = ...
      // Swap with larger child if node value is smaller
      if (items[largerChildIndex] > items[subTreeNodeIndex])
      {
         swap(items[largerChildIndex], items[subTreeNodeIndex]);
         // Continue with the recursion at that child
         heapRebuild(largerChildIndex);
      }  // end if
   }  // end if
}  // end heapRebuild

Heap - Add


Heap - Remove


Implementing Priority Queue as a Heap

Highest priority is at the root of MaxHeap


BST vs Heap in Implementing Priority Queue

If we know the maximum number of items in priority queue, heap is better

Heap is blanced, BST can become unbalanced degrading performance

If multiple items have the same priority, we can maintain a list at the node

When last item in the list deleted, node is deleted


Heap Sort - Sort an Arry Using Heap


Group Exercise

Start with array [25 30 20 80 40 60]

  1. Turn the given array into a heap
  2. Sort the array by removing root at each turn - draw the array after each swap and heapRebuild

Graphs


Graphs - Implementing


Graphs - Searching


Graphs - Group Exercise

  1. DFS, start at i, looking for e, mark all nodes visited
  2. BFS, start at i, looking for e, mark all nodes visited

After Class