I lost the βbitβ while trying to print a binary tree, as shown below in C ++:
8 / \ / \ / \ 5 10 / \ / \ 2 6 9 11
I know how to get the height of the tree and the number of nodes at each level, but I could not figure out how to set the correct number of spaces between the root and the second level (there are 3 lines under the root for 3 levels, but I believe that this is not so every time I thought it could be 3 times the height for large trees).
I would like to have some help to print these spaces in lines and the number of lines between lines. Thanks.
I am coding in C ++
Get height int tree::getHeight(No *node) { if (node == NULL) return 0; return 1 + max(getHeight(node->esq), getHeight(node->dir)); } Get number of nodes per line void tree::getLine(const No *root, int depth, vector<int>& vals){ int placeholder = 10; if (depth <= 0 && root != nullptr) { vals.push_back(root->chave); return; } if (root->esq != nullptr) getLine(root->esq, depth-1, vals); else if (depth-1 <= 0) vals.push_back(placeholder); if (root->dir != nullptr) getLine(root->dir, depth-1, vals); else if (depth-1 <= 0) vals.push_back(placeholder); }
source share