Professional Documents
Culture Documents
CS20L-Lecture Set 11 - Binary Heap
CS20L-Lecture Set 11 - Binary Heap
Completeness
The tree is complete, which means that nodes are
added from top to bottom, left to right, without
leaving any spaces. A binary tree is completely full if
it is of height, h, and has 2h+1-1 nodes.
Heapness
The item in the tree with the highest priority is at the
top of the tree, and the same is true for every
subtree.
Binary Heap
Binary tree of height, h, is complete iff
it is empty
or
its left subtree is complete of height h-1
and its right subtree is completely full of
height h-2
or
its left subtree is completely full of height
h-1 and its right subtree is complete of
height h-1.
Binary Heap
In simple terms:
Algorithm:
54 54 87 87
87 54 54 27
87 87 87
54 27 67 27 67 27
67 54 54 19
Binary Heap
54, 87, 27, 67, 19, 31, 29, 18, 32, 56, 7, 12, 31
87 87
67 27 67 27
54 19 19 31
54
Binary Heap
54, 87, 27, 67, 19, 31, 29, 18, 32, 56, 7, 12, 31
87
87
67 31 67 31
54 19 27 29
54 19 27 29
29 18
etc…
Binary Heap
To delete an element from the heap:
Algorithm:
If node is a leaf, delete it
Else if node has a right child, locate the
deepest leaf of right subtree and
replace node with that leaf. Then re-
heapify
Else replace node with the left child.
Binary Heap
Example: Deleting the root node, T
Binary Heap
Binary Heap
Binary Heap