top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Print a tree.

+5 votes
271 views

Print tree in this form.

                9

        5               15

    2       7       12      17  
  1   4  6    8  11   13  16  19
posted Oct 12, 2013 by Diya Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+4 votes
void print_level(node *root, int space, int level, int currlevel)
{
        int i =0;
        if ( currlevel == level )
        {
                for (i = 0; i < space; i++)
                        printf(" ");

                if (root == NULL)
                        printf(" ");
                else
                        printf("%d",root->data);

                for (i = 0; i < space; i++)
                        printf(" ");

        }
        else
        {
                if(!root)
                {
                        print_level(NULL, space, level, currlevel + 1);
                        print_level(NULL, space, level, currlevel + 1);
                }
                else
                {
                        print_level(root->left, space, level, currlevel + 1);
                        print_level(root->right, space, level, currlevel + 1);
                }
        }
}

void print_tree(node *tree)
{
        int hght = height(tree);
        int width = (1 << ( hght + 1)) - 1;
        int space = width / 2; int i;
        for (i = 1; i <= hght; i++)
        {
                print_level(tree, space, i, 1);
                printf("\n\n");
                space = space / 2;
        }
}
answer Oct 12, 2013 by Vikas Upadhyay
Similar Questions
+7 votes

Print cousins of a given node (Not sibling) ??

+7 votes
     50
    /  \
   20   30
   / \
  70  80
 /  \   \
10   40  60        

printing the border elements anticlockwise direction:
->50->20->70->10->40->60->30

+6 votes
The input tree is as shown below
            40
            / \
        20      60
        / \       \
    10      30      80
      \            /  \ 
       15        70    90

Output: 15 30 60 80 90
+5 votes
            1
    2               3

4       5       6       7

              8    9
            10 11

OUT PUT => 1 2 3 7 6 5 4 8 9 11 10

...