diff --git a/07-heaps/Heap.cpp b/07-heaps/Heap.cpp index 670b432..57e5675 100644 --- a/07-heaps/Heap.cpp +++ b/07-heaps/Heap.cpp @@ -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); + +} diff --git a/07-heaps/Heap.h b/07-heaps/Heap.h index 7060546..4c35e19 100644 --- a/07-heaps/Heap.h +++ b/07-heaps/Heap.h @@ -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 diff --git a/07-heaps/main.cpp b/07-heaps/main.cpp index 6266d12..867ae27 100644 --- a/07-heaps/main.cpp +++ b/07-heaps/main.cpp @@ -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 @@ -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; +}