Tutorial Solutions Week 04

Exercise 1

Heap

Consider the heap-as-array ADT given in lectures:

typedef struct HeapRep {
   Item *items;  // array of Items
   int  nitems;  // #items in array
   int  nslots;  // #elements in array
} HeapRep;
typedef HeapRep *Heap;

If a heap is created to hold up to 10 Items, and Items are integer values, and higher values have higher priority, show the state of the heap after each of the following operations:

Heap h;  Item it;
h = newHeap(10);
insert(h, 10);
insert(h, 5);
insert(h, 15);
insert(h, 3);
insert(h, 16);
insert(h, 13);
insert(h, 6);
it = delete(h);
insert(h, 2);
it = delete(h);
it = delete(h);
it = delete(h);
it = delete(h);
it = delete(h);

Repeat the above sequence of insertions an deletions, but this time draw the heap as a binary tree, with the highest value at the root and the values decreasing as you move down any branch.

Exercise 2

Balanced Trees

Derive a formula for the minimum height of a BSTree containing n nodes. You might find it useful to start by considering the characteristics of a tree which has minimum height. The following diagram may help:

Exercise 3

Balanced Trees

Explain how we could globally balance a binary search tree using the partition function.

Exercise 4

Splay Tree4