### Intro to the Heap data structure

• Definition: complete binary tree

• Complete binary tree:

 Complete binary tree = a binary tree where all levels, except possibly the last level are completely filled with nodes Furthermore: the last level has all its nodes to the left side

• Examples of complete binary trees:

• A perfert binary tree is a complete binary tree: • The last level does not need to be filled up: All the nodes must be packed on the left side !!!

• These are not complete binary trees:

• Levels are not not completely filled: • Nodes on the last level are not packed to the left: • Heap: another kind a binary tree

• Heap:

 Heap = a complete binary tree where the value in every node x is the smallest value in the subtree rooted at node x

• Example: the following complete binary tree is a heap because:

• Node 1 has the smallest value in the subtree rooted at node 1: • Node 5 has the smallest value in the subtree rooted at node 5: • Node 6 has the smallest value in the subtree rooted at node 6: So:

 the value in every node x is the smallest value in the subtree rooted at node x

• The following complete binary tree is not a heap: Because:

• The following subtree rooted at node 11 has the smallest value stored in a node that is not the root node of the subtree: • Priority queue

• Priority:

 Priority = a value that states the rank of urgency that a certain task must be executed A job with a higher priority is given a smaller ranking value

• Representing a priotity using a heap

• Fact:

• The root node in a heap always has the smallest value

 This follows directly from the definition of a heap !!!

• Representing a priority queue using a heap:

• The job with the highest priority will always be stored in the root node of a heap

In fact:

 The heap data structure is often used to store jobs that need to be ranked by their priorities

That's why a heap is sometimes called a priority queue

We will learn (study) algorithm used to:

• insert a new value into a heap

 After inserting, the resulting structure must still be a heap

• delete a node (value) from a heap

 After deleting, the resulting structure must still be a heap