【问题标题】:Print a binary search tree with depth打印具有深度的二叉搜索树
【发布时间】:2020-05-07 18:36:08
【问题描述】:

我需要打印一个深度从高到低的二叉搜索树, 在打印节点之前,根据深度会增加破折号的数量。树的根用 0 破折号,她的 silbings 用 1 个破折号... 我可以打印没有破折号的树,但我不知道如何用破折号打印。 我正在使用 C。 对不起我的英语不好

【问题讨论】:

    标签: c printing tree binary-search-tree


    【解决方案1】:

    有两种方法可以实现这一点。递归或保持节点的深度。

    1- 您可以使用如下递归代码

    void printnode (bststruct *node, int depth)
    {
        int i;
        for(i=1;i<=depth;i++) printf("-");
        printf("%d\n",node->value);
        if(node->left !=null) printnode(node->left,depth+1);
        if(node->right !=null) printnode(node->right,depth+1);
    }
    

    在您的主函数或您为此操作运行的任何函数中,只需调用printnode(root,0)

    2- 另一种方法是在每个节点中保留一个专用的深度值。如果您不打算将该值用于任何其他目的,请执行第一个选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 2015-04-08
      • 2010-12-24
      • 1970-01-01
      相关资源
      最近更新 更多