10.8 Lab: Heap - Display Heap as an Indented List

Change the previous lab to display a min-heap as an indented list (level numbers included). In order to do this you will have to add two new member functions to the heap class

- void _printIndented(int index, void visit(int, int)); // A
- void printIndented(void visit(int, int)); // B

Note: One function would be sufficient(A). However, to make the call simpler, a wrapper function (B) has been added (to "hide" the root of the heap).

Another solution is to add level as a parameter to _printIndented:

- void _printIndented(int index, int level, void visit(int, int));
This commit is contained in:
Iurii Tatishchev 2024-05-28 18:59:23 -07:00
parent eb1cf4176f
commit cc06e5fbdb
Signed by: CaZzzer
GPG Key ID: 9A156B7DA6398968
3 changed files with 35 additions and 8 deletions

View File

@ -83,3 +83,12 @@ bool Heap::deleteHeap(int &returnItem) {
return true;
}
void Heap::_printIndented(int index, int level, void (*visit)(int item, int level)) {
if (_findRightChild(index) != -1)
_printIndented(_findRightChild(index), level + 1, visit);
visit(heapAry[index], level);
if (_findLeftChild(index) != -1)
_printIndented(_findLeftChild(index), level + 1, visit);
}

View File

@ -49,6 +49,11 @@ public:
bool insertHeap(int itemIn);
bool deleteHeap(int &itemOut);
// other functions added
void printIndented(void visit(int item, int level)) { _printIndented(0, 0, visit); };
void _printIndented(int index, int level, void visit(int item, int level));
};
#endif

View File

@ -1,7 +1,8 @@
/*
This program will read integers from the keyboard,
insert them into a min-heap, and display them as
they are deleted from the heap.
This program will
- read integers from the keyboard and insert them into a min-heap,
- display the min-heap as an indented list (level numbers included) and
- display the integers as they are deleted from the heap.
*/
#include <iostream>
@ -9,11 +10,11 @@
using namespace std;
void iDisplay(int item, int level);
int main() {
Heap heap;
// build heap
int num;
cout << "Enter integers [0 - to stop]" << endl;
@ -22,14 +23,14 @@ int main() {
heap.insertHeap(num);
cin >> num;
}
cout << "Heap capacity: " << heap.getSize() << endl;
cout << "Heap actual number of elements: " << heap.getCount() << endl;
heap.printIndented(iDisplay);
// print items as they are deleted from the heap (sorted)
if (heap.isEmpty()) {
if (heap.isEmpty())
cout << "N/A";
}
while (!heap.isEmpty()) {
heap.deleteHeap(num);
cout << num << " ";
@ -38,3 +39,15 @@ int main() {
return 0;
}
/*
indented display:
displays one item including the level number
and corresponding indentation
*/
void iDisplay(int item, int level) {
for (int i = 0; i < level; i++)
cout << "..";
cout << level << "). " << item << endl;
}