Deja123 Deja123 - 3 years ago 129
C Question

How to print elements from Binary Tree by level in c

I got binary tree, not BST, so elements are not sorted, and information that every node holds is string type.
When I am printing elements that hold integers in BST I do it with recursion like this: (in_order printing)

void PrintElements(const Data* node)
{
// Check if its empty
if (node == NULL)
return;

PrintElements(node->left);
printf(" %d\n", node->key);
PrintElements(node->right);
}


But I can't figure out how to print them by level in binary tree holding strings that are not sorted (alphabetically).. Any help is greatly appreciated.

Answer Source

You have to implement some auxiliar functions in order to print by level in a recursive way:

First, you need a function that retrieves the level count of your tree

int getLevelCount(Data *node)
{
    if (node == NULL)
    {
        return 0;
    }
    int leftMaxLevel = 1 + getLevelCount(node->left);
    int rightMaxLevel = 1 + getLevelCount(node->right);
    if (leftMaxLevel > rightMaxLevel)
    {
        return leftMaxLevel;
    }
    else
    {
        return rightMaxLevel;
    }
}

Second, you have to implement a function that prints a specific level of the tree:

void printLevel(Data *node, int level)
{
    if (node != NULL && level == 0)
    {
        printf("%s\n", node->key);
    }   
    else if (node != null)
    {
        printLevel(node->left, level - 1);
        printLevel(node->right, level - 1);
    }
}

Last, you print every level of your tree (starting by the root node):

void printElements(Data *node)
{
    int i;
    int levelCount = getLevelCount(node);
    for (i = 0; i < levelCount; i++)
    {
        printLevel(node, i);
    }
}

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download