Upload
bruce-barnett
View
212
Download
0
Embed Size (px)
Citation preview
HEAPS
TWO KINDS OF HEAPS: MAX AND MIN
Max: Every child is smaller than its parent Meaning the max is the root of the tree
10
/ \
9 7
/ \
6 8
/ \
2 4
\
1
TWO KINDS OF HEAPS: MAX AND MIN
Min: Every child is larger than its parent Meaning the min is the root of the tree
3
/ \
9 4
/ \
16 18
/ \
22 34
\
109
WHEN TRYING TO STAY MOSTLY BALANCED
3 4 5
/ \
6 8
/ \
12 10
Let’s say 2 is our root, and we have these three heaps left to merge. Which do you merge to stay mostly balanced?
WHEN TRYING TO STAY MOSTLY BALANCED
3 4 5
/ \
6 8
/ \
12 10
You want to merge the heap that is 3 with the heap with a root of 4
EX1: IS THIS A CORRECT MIN HEAP?
3
/ \
9 4
/ \
16 8
/ \
22 34
\
109
EX1: IS THIS A CORRECT MIN HEAP?
No. Why not?
3
/ \
9 4
/ \
16 8
/ \
22 34
\
109
EX1: IS THIS A CORRECT MIN HEAP?
The 8 is in the wrong place.
3
/ \
9 4
/ \
16 8
/ \
22 34
\
109
EX2: IS THIS A CORRECT MIN HEAP?
3
/ \
9 400
/ \
16 10
/ \
22 34
\
109
IS THIS A CORRECT MIN HEAP?
3
/ \
9 400
/ \
16 10
/ \
22 34
\
109
Yes!
IS THIS A CORRECT MIN HEAP?
3
/ \
9 400
/ \
16 10
/ \
22 34
\
109
This may look strange, but this is a valid min heap.
EX3: WHAT IS THIS?
7
/ \
3 8
/ \
2 4
/ \
1 5
\
6
EX3: IT’S A BINARY SEARCH TREE
7
/ \
3 8
/ \
2 4
/ \
1 5
\
6
This is a binary search tree. Remember:
Left is smaller than parent Right is greater than parent.
BINARY TREES VS BSTS VS HEAPS
Binary Tree Has left child and right child (only two children per node) No requirements regarding children’s keys and parent’s
key Binary Search Tree
A type of binary tree Requirement for children: left’s key is smaller than
parent’s key, and right’s key is greater than parent’s key Heap
A type of binary tree Max heap: Both children’s keys are less than parent’s key
(so maximum is root of tree) Min heap: Both children’s keys are greater than parent’s
key (so minimum is root of tree)
CHECKING IF MIN HEAP IS VALID
Check if left child is valid: Left child is larger than parent
or Left child is empty
Check if right child valid: Right child is larger than parent
or Right child is empty
If both of the above are true: Recursively run method on left child
&&Recursively run method on right child
If either of the above is false: You can stop now and just return false