如何在C中按级别打印二叉树中的元素 [英] How to print elements from Binary Tree by level in c

查看:129
本文介绍了如何在C中按级别打印二叉树中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的是二叉树,而不是BST,因此元素没有排序,每个节点保存的信息是字符串类型. 当我在BST中打印包含整数的元素时,我会像这样递归地进行打印:(按顺序打印)

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.

推荐答案

您必须实现一些辅助功能才能以递归方式按级别打印:

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);
    }
}

希望有帮助.

这篇关于如何在C中按级别打印二叉树中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆