Tricky question. Let's first look at a simpler problem: How to print the tree horizontally with the root to the left and the branches growing towards the right. This can be done without cursor positioning in the console window by keeping track of the indentation level:
void horizontal(struct btnode *t, int level)
{
int l = level;
if (t == NULL) return;
horizontal(t->l, level + 1);
while (l--) printf(" ");
printf("-> %d\n", t->value);
horizontal(t->r, level + 1);
}
Printing the tree from top to bottom is similar. The indentation is now the position from the top. The tricky part is how to advance printing to the right. In the simple console example, that is done by printing a new line. Here, we must advance the x
position. This can be done with a global variable x
, but you can also keep the state in a variable pointed to in the print function:
void print(struct btnode *nd, int *x, int y)
{
if (nd == NULL) return;
print(nd->l, x, y + 4);
gotoxy(*x, y);
printf("%d", nd->value);
*x += 4;
print(nd->r, x, y + 4);
}
Call the print
function like this:
int x = 0;
print(root, &x, 0);