gpt4 book ai didi

c - C中的二叉树崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:52 24 4
gpt4 key购买 nike

<分区>

我开始在我的 C 类中学习二叉树。我了解二叉树的概念,但现在我正试图更深入地了解它的工作原理。我试图建立一个简单的二叉树,它根据用户输入的内容改变大小。每当我运行程序时,它都会在第一次输入后崩溃。谁能帮我理解为什么?

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

typedef struct node
{
int value;
struct node *left;
struct node *right;
}node;

void traverse(node *root);
void addnode (node *root, int nUser);
int checknode (node *root, int nUser);

int main (void)
{
int nUser;
node *root;
root=(node *)malloc(sizeof(node));
root->value=10;
do
{
printf("Please enter any integer, enter 0 when done\n\n\n"); /*Program crashes when I enter the first value, unsure why*/
scanf("%d",&nUser);
if(!(checknode(root,nUser)))/*check node runs through the binary tree to find the data if it exists, returns 1 if exists, 0 if it doesn't*/
addnode(root,nUser); /*add node runs through the binary tree, when it finds a place where the number will fit, that is a null pointer where the number can be placed it will create a new node with the value and null pointers on right and left*/
}while(nUser);
traverse(root);/*should traverse the tree and print out values*/
return(0);
}

void traverse(node *root)
{
printf("%d/n",root->value);
if(root->left)
{
traverse(root->left);
}
if(root->right)
{
traverse(root->right);
}
}

void addnode (node *root, int nUser)
{
if(root->value<nUser)
if(root->right)
{
addnode(root->right,nUser);
}
else
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->value=nUser;
root->right=temp;
}
if(root->value>nUser)
if(root->left)
{
addnode(root->left,nUser);
}
else
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->value=nUser;
root->left=temp;
}
}
int checknode (node *root, int nUser)
{
if(!(root->value==nUser))
{
if(root->value<nUser)
if(root->right)
{
checknode(root->right,nUser);
}
else
{
return(0);
}
if(root->value>nUser)
if(root->left)
{
checknode(root->left,nUser);
}
else
{
return(0);
}
}
else
{
return (1);
}
}

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