我试图在编程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/