I'm trying to display a BST in console. That's my code (it's a modified version of code found here: Printing Level Order Binary Search Tree Formatting):
string printLevel(node *root, int level, string gap) {
if (!root) {
return gap + "-" + gap;
}
if (level==1) {
stringstream out;
out<<root->value;
return gap + out.str() + gap;
} else if (level>1) {
string leftStr = printLevel(root->left, level-1, gap);
string rightStr = printLevel(root->right, level-1, gap);
return leftStr + " " + rightStr;
} else return "";
}
void printLevelOrder (node* root, int depth) {
for (int i=1; i<=depth; i++) {
string gap="";
for (int j=0; j<pow(2,depth-i)-1; j++) {
gap+=" ";
}
string levelNodes = printLevel(root, i, gap);
cout<<levelNodes<<endl;
}
}
For example result should be like that:
4
1 6
- 2 5 -
- - - 3 - - - -
But instead it is:
4
1 6
- 2 5 -
- - 3 - - -
If I undestand correctly, the recursion stops when the program makes it to the empty leaf and therefore there are lacking " - " on the lower levels in the result. But how do I know how much of those I should draw on the lower levels? How to make this work?
3is displayed, it should be to the right of2.3would have been on its place. In the means of data structure, it is a right child of the2.