c - c语言编程中二叉树实现代码的问题

标签 c data-structures

我试图在编程c中实现二叉树。它仅获取值,但不显示任何预期结果。需要帮助来实现二叉树。在这里我添加了我尝试了很长时间的代码。

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node*left;
    struct node*right;
};
int i,parent;
struct node*root=NULL;
struct node*newnode,*temp[];
void display(struct node*);

void display(struct node *root)
{
   if(root != NULL){
      printf("%d\t",root->data);
      display(root->left);
      display(root->right);
   }
}
void add(int num)
{
    for(i=0;i<num;i++)
    {
       newnode=(struct node*)malloc(sizeof(struct node));
       newnode->left=newnode->right=NULL;
       newnode->data=i+1;

        if(i==0)root=newnode;continue;
        parent=(i-1)/2;

        if(i%2==0)temp[parent]->right=newnode;

        else temp[parent]->left=newnode;

    }
}
int main()
{
    int num;
    printf("enter a binary number:");
    scanf("%d",&num);
     display(root);

}

最佳答案

您是否尝试过在显示二叉树之前向其添加数据?

新答案: 我修改了您的代码以按如下方式排列数据。我希望这就是您想要做的事情

       1
   2      3
 4   5  6   7 etc

#include <conio.h>
#include <stdlib.h>
#include <stdio.h>


struct node
{
    int data;
    struct node*left;
    struct node*right;
};

int i, parent;
struct node*root = NULL;
struct node*newnode, *temp[20];

void display(struct node *root)
{
    if (root != NULL) {
        printf("%d\t", root->data);
        display(root->left);
        display(root->right);
    }
}

void add(int num)
{
    for (i = 0; i<num; i++)
    {
        newnode = (struct node*)malloc(sizeof(struct node));
        newnode->left = newnode->right = NULL;
        newnode->data = i + 1;
        temp[i] = newnode;
        if (i == 0)
        {
            root = newnode;
            continue;
        }
        parent = (i - 1) / 2;

        if (i % 2 == 0) temp[parent]->right = newnode;

        else temp[parent]->left = newnode;


    }
}

int main()
{
    int num;
    printf("enter a binary number (Max 20):");
    scanf("%d", &num);
    add(num);
    display(root);

}

您所犯的错误是没有将临时值引用到任何内容,也没有定义数组而不精确确定大小。

关于c - c语言编程中二叉树实现代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40872401/

相关文章:

创建字符链表并打印

C++ 图实现

c - 使用变量作为函数参数和直接使用字符串作为函数参数有什么区别?

c - 我如何禁用 Lex 中的最大咀嚼规则?

c - 了解 memcpy() 的源代码

algorithm - 创建平衡二叉搜索树的时间复杂度?

data-structures - 可变 Haskell 堆的类型签名

c++ - 有效地计算阶乘

c - 为什么将 double 转换为 int 可能会产生不同的结果?

c - 在 Windows 上使用 scanf 查找字符串时双击 Ctrl+D 输入