Search code examples
cbinary-treebinary-search-tree

How to print a binary search tree in level order, including the null values


So right now, when I have a tree that looks like:

       5
         \
          6
           \
            7
             \
              9

I can print this in level order so that

5, 
6, 
7, 
9, 

this is printed

However, I want to make it so that it prints something like this:

5,
0, 6,
0, 0, 0, 7,
0, 0, 0, 0, 0, 0, 0, 9, 

So that all the NULL nodes are also printed as 0.

void current_height(tree *root, int level){
    if(root == NULL){
        return;
    }
    if(level == 1){
        printf("%d, ", root->data);
    }
    else if(level > 1){
        current_height(root->left, level - 1);
        current_height(root->right, level - 1);
    }
}

This is the code I have so far

BTW, I also thought about putting an index into struct tree so that I could change the tree into an array and just print the array. But I found that it would make the deleting function too complicated so I didn't use that idea


Solution

  • You have to simulate tree content which is not there.
    Since you have the info on the relative target level as your additional parameter already in place that is not hard.
    Just invent more tree nodes in case of NULL pointers before the target depth, always giving NULL as invented pointer.

    void current_height(tree *root, int level){
        if(root == NULL){
            if (level>1){
                current_height(NULL, level - 1);
                current_height(NULL, level - 1);
            }
            else {
                printf("%d, ", 0);
            }
            return;
        }
        if(level == 1){
            printf("%d, ", root->data);
        }
        else if(level > 1){
            current_height(root->left, level - 1);
            current_height(root->right, level - 1);
        }
    }
    

    Output here https://www.onlinegdb.com/online_c_compiler is:

    5, 
    0, 6, 
    0, 0, 0, 7, 
    0, 0, 0, 0, 0, 0, 0, 9,