Skip to content
This repository was archived by the owner on Nov 29, 2020. It is now read-only.

Commit 4ac3599

Browse files
committed
add a print_tree style
1 parent 7da3102 commit 4ac3599

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

BTree.cpp

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#define FUNC_BTree
2626

2727
#include <map>
28+
#include <iomanip>
2829
#include "utils.h"
2930

3031
size_t debug;
@@ -324,20 +325,35 @@ class BTree {
324325
}
325326
return ans;
326327
}
327-
void print_tree(BNode<T>* x, size_t depth) {
328-
std::string indent(4 * depth, ' ');
329-
std::cout << indent << "___" << std::endl;
328+
void print_tree(BNode<T>* x, size_t depth, bool term) {
329+
const size_t ind = 4;
330+
const std::string indent(ind * depth, ' ');
331+
if (!term)
332+
std::cout << indent << std::string(3, '_') << std::endl;
330333
for (size_t i = 0; i <= x->n; i++) {
331334
if (!x->leaf)
332-
print_tree(x->c[i], depth + 1);
335+
print_tree(x->c[i], depth + 1, term);
333336
if (i == x->n)
334337
break;
335-
std::cout << indent << x->key[i] << std::endl;
338+
std::cout << indent;
339+
if (term) {
340+
if (i == 0)
341+
std::cout << "\033[53m";
342+
if (i == x->n - 1)
343+
std::cout << "\033[4m";
344+
}
345+
std::cout << std::left << std::setw(ind - 1) << x->key[i];
346+
if (term)
347+
std::cout << "\033[0m";
348+
std::cout << std::endl;
336349
}
337-
std::cout << indent << "^^^" << std::endl;
350+
if (!term)
351+
std::cout << indent << std::string(3, '^') << std::endl;
338352
}
339-
void print_tree() {
340-
print_tree(root, 0);
353+
void print_tree(bool term) {
354+
std::cout << std::endl;
355+
print_tree(root, 0, term);
356+
std::cout << std::endl;
341357
}
342358
~BTree() { delete root->recursive_destruct(); }
343359
BNode<T> *root;
@@ -353,7 +369,7 @@ int main(int argc, char *argv[]) {
353369
std::cout << "s / S: search" << std::endl;
354370
std::cout << "i / I: insert" << std::endl;
355371
std::cout << "d / D: delete" << std::endl;
356-
std::cout << "p / P: print tree" << std::endl;
372+
std::cout << "p / P: print tree (two styles)" << std::endl;
357373
std::cout << "q / Q: quit" << std::endl;
358374
// Generate tree in Page 498, Figure 18.7 (a):
359375
// i10 i11 i13 i14 i15 i1 i3 i7 i4 i5 i16 i18 i19 i24 i25 i26 i20 i21 i22
@@ -388,8 +404,10 @@ int main(int argc, char *argv[]) {
388404
std::cout << std::boolalpha << BT.BTreeDelete(x) << std::endl;
389405
break;
390406
case 'p':
407+
BT.print_tree(true);
408+
break;
391409
case 'P':
392-
BT.print_tree();
410+
BT.print_tree(false);
393411
break;
394412
case 'q':
395413
case 'Q':

0 commit comments

Comments
 (0)