编译时似乎有错误但不确定是什么。我已经完成了所有这几次,无法弄清楚原因。
另外,我是否还应该做些其他事情来改进这段代码?
#include <stdlib.h>
#include <stdio.h>
//create structure to hold node
typedef struct node
{
int data;
struct node *left; //lower no. / points to left node
struct node *right; //higher no. / points to right node
} node;
void insert(node **rt, int val) //insertion function
{
node *tmp;
if(*rt == NULL){
tmp = (node *) malloc(sizeof(node)); //allocates memory for node
if (tmp == NULL)
{
printf(stderr, "Unable to allocate node\n");
exit(1);
}
tmp->data = val;
*rt = tmp;
}
else{
if(val > (*rt)->data)
insert(&(*rt)->right, val);
else
insert(&(*rt)->left, val);
}
}
void print_node(node *head) //starts with head/first node until NULL
{
if(head == NULL)
return;
if(head->left != NULL)
print_node(head->left);
printf("data = %d\n", head->data);
if(head->right != NULL)
print_node(head->right);
}
int main(int argc, char *argv[])
{
int value[6] = {20,10,5,17,30,21}; //values put into array
int i; //i count
node *head = NULL;
for(i = 0; i < 6; i++) //loop array
{
insert(&head, value[i]);
}
print_node(head); //recursive search
return 0;
}
答案 0 :(得分:1)
代码似乎错过了初始化新分配left
的{{1}}和right
成员。
在此行之后修复此插入
node
缺少这样的初始化:
tmp->data = val;
此外,代码错过了打印出正确节点的值。
答案 1 :(得分:0)
在这一行printf(stderr, "Unable to allocate node\n");
我认为你的意思是fprintf(stderr, "Unable to allocate node\n");