【发布时间】:2018-11-28 22:17:35
【问题描述】:
这是我创建和插入二叉搜索树的代码
struct BTNode
{
int info;
struct BTNode *left, *right;
};
struct BTNode* create(int data)
{
struct BTNode *root;
struct BTNode *n = malloc(sizeof(struct BTNode));
n->info = data;
n->left = NULL;
n->right = NULL;
root = n;
return(root);
}
struct BTNode* insert(struct BTNode *root, int data)
{
struct BTNode *ptr;
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL)
printf("\nOUT OF MEMORY!\n");
n->info = data;
n->left = NULL;
n->right = NULL;
ptr = root;
while (ptr != NULL){
if (data < ptr->info){
if (ptr->left == NULL)
ptr->left = n;
ptr = ptr->left;
}
else if (data > ptr->info){
if (ptr->right == NULL)
ptr->right = n;
ptr = ptr->right;
}
}
return(n);
}
这里是 main() 函数
int main()
{
struct BTNode *root = NULL;
int choice, data;
printf("\nWrite the root data: ");
scanf("%d", &data);
root = create(data);
while (1){
printf("\n1.Insert 2.Preorder 3.Exit\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("\nWrite the data: ");
scanf("%d", &data);
insert(root, data);
break;
我能够创建根节点,但每当我尝试插入数据时,我都会提供我的数据,编译器会停止执行任何操作。知道为什么会这样吗?
【问题讨论】:
-
为什么不和你的同学合作:stackoverflow.com/questions/50935603/…?
-
@ChristianGibbons 不。在这种情况下,我的 while 循环将永远运行。为什么会这样?
标签: c function tree malloc binary-search-tree