gpt4 book ai didi

c - C语言插入数据到二叉树

转载 作者:太空宇宙 更新时间:2023-11-04 04:13:25 25 4
gpt4 key购买 nike

所以基本上我正在开发一个简单的程序来将数据插入二叉树。程序为 15 的整数变量调用函数,该变量将成为头节点,然后为 12 的变量调用相同的函数,它应该在根节点的左分支上实现新数据。不幸的是,虽然第一部分工作正常,并且根节点被打印出来,但是当新值应该为根节点的左分支实现时,什么也没有发生。欢迎任何提示和建议。谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int data;
struct node *right;
struct node *left;
} NODE;
void *insert(int ins, NODE *start)
{
NODE *newNode = malloc(sizeof(NODE));
if (start == NULL )
{
newNode->data = ins;
newNode->left = NULL;
newNode->right = NULL;

}
if(ins<start->data)
{
insert(ins, start->left);
}
else if(ins>start->data)
{
insert(ins, start->right);
}
}
int main()
{
int number;
NODE *head;
head=NULL;

number = 15;
head = insert(number, head);
printf("prints the first element (head): %d", head->data);

number = 12;
insert(number, head);

printf("should print the left branch : %d", head->left->data); // <- THIS DOES NOT SHOW UP

}

最佳答案

start 参数是按值传递的,因此永远不会被修改。您的选择之一是将指针传递给 NODE 的指针,如下所示:

void insert(int ins, NODE **start)
{
if (*start == NULL )
{
NODE *newNode = (NODE *)malloc(sizeof(NODE));
newNode->data = ins;
newNode->left = NULL;
newNode->right = NULL;
*start = newNode;
}
if(ins< (*start)->data)
{
insert(ins, &(*start)->left);
}
else if(ins> (*start)->data)
{
insert(ins, &(*start)->right);
}
}

int main()
{

int number;
NODE *head;
head=NULL;

number = 15;
insert(number, &head); ///Doesn't need head=insert(...) anymore
printf("prints the first element (head): %d", head->data);

number = 12;
insert(number, &head);

printf("should print the left branch : %d", head->left->data);
}

关于c - C语言插入数据到二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com