How to print elements from Binary Tree by level in c [closed]

半世苍凉 提交于 2020-08-05 07:03:12

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37062169/how-to-print-elements-from-binary-tree-by-level-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!