c - 如何水平显示我的二叉树?

标签 c

我正在研究二叉搜索树,我对递归的概念并不是最好的。所以我选择使用递归来完成所有基本任务。唯一的问题是我的显示功能。我可以打印出所有节点及其各自的根节点,但不是在同一行上打印,而是在多行上打印。 输出:

我尝试使用 if else 语句在不为空时调用左子树和右子树,但我仍然得到相同的输出。

node_tree *display(node_tree *ref, int spaces){
        if (ref==NULL)
           return ref; 

        spaces = spaces/2; 
        for(int j = 0 ; j< spaces; j++)
         printf(" "); 
        printf("%d\n", ref->data);
        //display(ref->left, spaces); 
        //printf("\n");
        //printf("%d", ref->data);
        //display(ref->right, spaces);new after this line
        if (ref->left!=NULL&&ref->right!=NULL){
          display(ref->right, 3*spaces); display(ref->left, spaces);
        }   
        else if(ref->right ==NULL){
          display(ref->left, spaces);
        }
        else if(ref->left ==NULL){
          display(ref->right, 3*spaces);
        }

        //else
        //printf("%d\n", ref->data); 
    }

输出

       12
         13
   10
     11
  9

预期输出

       12
    10    13
  9  11

最佳答案

如果左内部节点有两个特定的外部节点并且中序遍历; 你可以尝试一下:

<code>
int  node_height(node* node)
{
    int u, v;

    if (node == NULL)
        return -1;

    u = node_height(node->left);
    v = node_height(node->right);

    if (u > v)
        return u + 1;
    else
        return v + 1;
}

void node_print(char* ch, int height)
{
    int i;

    for (i = 0; i < height; i++)
        printf(" ");

    printf("%c", ch);
}

void node_show(node* node, int height)
{

    if (node == NULL) {
        node_print('*', node_height(node));

        return;
    }

    node_show(node->right, node_height(node) + 1);
    node_print(node->item, node_height(node));
    node_show(node->left, node_height(node) + 1);
}
</code>

调用给定高度的node_show(node, node_height(node))函数。

关于c - 如何水平显示我的二叉树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58467448/

相关文章:

c - 为什么我不需要在打印之前取消引用 C 中的字符指针?

c - BMP 中的棕褐色泛音滤镜

c++ - 窗口名称未打印

c - 来自 Kernighan 和 Ritchie 的原始 C 你好,世界程序未编译

c - 向指针添加一个数字

c - c中的多分支树

c - 用于密码的 PBKDF2-HMAC-SHA1——C 中的示例?

c - 在循环外使用变量,值在循环内变化

c++ - 将函数的当前状态传递给 C/C++ 中的另一个函数

连接 int 和 FILE* (C/C++)