This preview shows pages 1–3. Sign up to view the full content.
1
1
Trees
6B
2
Heap
A minheap
is a binary tree such that
 the data contained in each node is less than
(or equal to) the data in that node’s children.
 the binary tree is complete
A maxheap
is a binary tree such that
 the data contained in each node is greater than
(or equal to) the data in that node’s children.
 the binary tree is complete
3
Is it a minheap?
5
14
23
20
16
48
62
53
71
4
Is it a minheap?
5
14
23
12
26
34
20
24
35
5
Is it a minheap?
5
14
23
32
87
90
50
64
53
41
6
Using heaps
What are minheaps good for?
(What operation is extremely fast when
using a minheap?)
The difference in level between any two leaves
in a heap is at most what?
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document2
7
Storage of a heap
Use an array to hold the data.
Store the root in position 0.
For any node in position i,
 its left child (if any) is in position 2i + 1
 its right child (if any) is in position 2i + 2
 its parent (if any) is in position (i1)/2
(use integer division)
8
53
9
64
50
90
87
41
32
23
14
5
8
7
6
5
4
3
2
1
0
5
14
23
32
87
90
50
64
53
41
Storage of a heap
For node at i:
Left child is at 2i+1
Right child is at 2i+2
Parent is at
(i1)/2
9
Inserting into a minheap
Place the new element in the next available
position in the array.
Compare the new element with its parent. If the
new element is smaller, than swap it with its
parent.
Continue this process until either
 the new element’s parent is smaller than or
equal to the new element, or
 the new element reaches the root (index 0 of
the array)
10
Inserting into a minheap
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '09
 ReidMiller

Click to edit the document details