【问题标题】:Cannot print binary tree with indentation无法打印带有缩进的二叉树
【发布时间】:2019-11-01 13:49:48
【问题描述】:

我有二叉搜索树

        c
    b      d
a             e
                  f

我想打印

c
  b
    a
  d
    e
      f

不保存每个节点的深度。我试过了:

typedef struct _bst_t 
{
    char word[MAX_WORD_LEN];
    struct _bst_t *left;
    struct _bst_t *right;
} bst_t;

    void bst_print(bst_t *bst)
    {
        if (bst != NULL)
        {
            printf("%s\n", bst->word);
            printf(" ");
            if (bst->left != NULL)
                bst_print(bst->left);
            if(bst->right != NULL)
                bst_print(bst->right);
        }
    }

我应该如何更改此代码?

哦。很抱歉,没有提供每个节点的深度。我应该创建一个新函数来获取每个节点的深度吗??

【问题讨论】:

  • 该问题无法回答,因为没有足够的信息。请阅读以下内容:How to Askedit 您的问题并显示minimal reproducible example
  • 就个人而言,我认为这里有足够的代码来理解问题,尽管您应该包括它当前显示的内容以使生活更轻松。
  • @waniwani 所有单词的长度都一样吗?
  • @VladfromMoscow 在此示例中,我使用了 a、b、c、d、e、f,但 bst_t->word 用于保存单词。所以它可以是不同长度的单词。
  • 看看下面的答案(他们都说基本相同)。您不需要函数来获取每个节点的深度,深度是通过递归深度隐式知道的。

标签: c binary-tree binary-search-tree


【解决方案1】:

递归函数需要知道当前深度,以便打印所需的空格数。这可以通过将depth 参数添加到递归函数来完成。在递归调用中传递当前深度加 1。

为避免向主 bst_print 函数添加额外参数,可以将递归部分移至辅助函数,并将额外参数初始设置为 0。

void bst_print_(bst_t *bst, unsigned int depth)
{
    if (bst != NULL)
    {
        for (unsigned int i = 0; i < depth; i++)
            printf(" ");
        printf("%s (%d)\n", bst->word, bst->count);
        if (bst->left != NULL)
            bst_print_(bst->left, depth + 1);
        if(bst->right != NULL)
            bst_print_(bst->right, depth + 1);
    }
}

void bst_print(bst_t *bst)
{
    bst_print_(bst, 0);
}

【讨论】:

  • 非常感谢。 if (bst->left != NULL) bst_print_(bst->left, depth + 1); if(bst->right != NULL) bst_print_(bst->right, depth + 1);应该改为 if (bst->left != NULL) bst_print2(bst->left, depth + 1); if(bst->right != NULL) bst_print2(bst->right, depth + 1);使用此代码解决了问题。 :)
【解决方案2】:

您的问题在于缩进(我认为),解决方案是在递归时随身携带缩进。

  1. bst_print 添加第二个参数。要么void bst_print(bst_t *bst, int depth) (更纯粹,更普遍有用)或void bst_print(bst_t *bst, string indent)(直接适用于打印)。
  2. 每个子调用都应添加到值: bst_print(bst-&gt;left, depth+1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多