Presentation is loading. Please wait.

Presentation is loading. Please wait.

H EAPS. T WO 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.

Similar presentations


Presentation on theme: "H EAPS. T WO 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."— Presentation transcript:

1 H EAPS

2 T WO 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

3 T WO 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

4 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?

5 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

6 E X 1: IS THIS A CORRECT MIN HEAP? 3 / \ 9 4 / \ 16 8 / \ 22 34 \ 109

7 E X 1: IS THIS A CORRECT MIN HEAP? No. Why not? 3 / \ 9 4 / \ 16 8 / \ 22 34 \ 109

8 E X 1: IS THIS A CORRECT MIN HEAP? The 8 is in the wrong place. 3 / \ 9 4 / \ 16 8 / \ 22 34 \ 109

9 E X 2: IS THIS A CORRECT MIN HEAP? 3 / \ 9 400 / \ 16 10 / \ 22 34 \ 109

10 IS THIS A CORRECT MIN HEAP? 3 / \ 9 400 / \ 16 10 / \ 22 34 \ 109 Yes!

11 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.

12 E X 3: WHAT IS THIS? 7 / \ 3 8 / \ 2 4 / \ 1 5 \ 6

13 E X 3: 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.

14 B INARY T REES VS BST S VS H EAPS 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)

15 C HECKING I F M IN H EAP I S V ALID 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


Download ppt "H EAPS. T WO 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."

Similar presentations


Ads by Google