Question

I want to print the contents of my BST in a tree format like:

my current print output:

10 -> 20 -> 30 -> 40 -> 60 -> 80 -> 90 ->

what i want it to be like:

        40
        /\
       /  \
     20    60
     / \    \
   10  30   80
              \
              90

I tried doing some gotoxy but for some reason i just cant get it to print like a tree, i think i need to do more than just gotoxy though. Also "\" is not really necessary just an added feature to not confuse any of you.

The Code are as follows:

Structure:

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;

print:

void inorder(struct btnode *t)
{
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }
    if (t->l != NULL)    
        inorder(t->l);
        printf("%d -> ", t->value);
    if (t->r != NULL)    
        inorder(t->r);
}

my attempt in tree printing:

void print(struct btnode *t, int x, int i, int y)
{
    i = i / 2 + 2;
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }

    if (t->l != NULL){
        print(t->l, (x + i), i, (y + 1));
    }

    if (t->r != NULL){
        print(t->r, (x + i), i, (y + 1));
    }
    gotoxy(x, y * 2);
    printf("%d -> ", t->value);
}

Any idea on how I can achieve the tree output base on my current output code, though I assume that i need to do some more if and else to turn it as a tree. anything would be of help, a guide or an idea would really be appreciated.

thank you

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top