I am a "bit" lost trying to print a binary tree like 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 in each level, but I couldn't figure out how to set the right number of spaces between the root and the second level (there are 3 lines under the root for 3 levels but I believe it is not this everytime,I thought it could be 3 times the height for greater trees).
I would like to have some help to print these spaces in the rows and the number of lines between the rows.Thank you.
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& 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);
}