【发布时间】:2020-01-30 23:09:43
【问题描述】:
我正在尝试做一个将值插入二叉树的函数。 insertbin(...) 中的第一个 while 循环在它移动到下一个元素后等于 NULL 时完全忽略 x 值。我的情况有什么问题吗?
我已经尝试使用 prev 节点来检查条件,但它仍然不起作用。
#include <stdlib.h>
#include <stdio.h>
#include "Queue_arr.h"
tree* createtree() {
tree*mytree = (tree*)malloc(sizeof(tree));
mytree->root = NULL;
return mytree;
}
void insertbin(tree* T, int data) {
treenode *x, *y, *z;
int flag = 1;
z = (treenode*)malloc(sizeof(treenode));
y = NULL;
x = T->root;
z->key = data;
while (x != NULL) //While the tree isn't empty
{
y = x;
if (z->key < x->key) //If the data is smaller than the existing key to the left
x = x->sonleft;
else //Else, to the right
x = x->sonright;
}
z->father = y;
if (y == NULL) //If y is the root
T->root = z;
else
if (z->key < y->key) //If the data is smaller than the existing key to the left
y->sonleft = z;
else //Else, to the right
y->sonright = z;
}
void insertscan(tree *T) //Scans the data to insert to the tree via insertbin(...)
{
int data;
printf("Enter a number (Enter a negative number to stop): \n");
scanf("%d", &data);
while (data >= 0)
{
insertbin(T, data);
scanf("%d", &data);
}
}
void main()
{
tree* T;
T = createtree();
insertscan(T);
}
【问题讨论】:
-
请删除任何与当前问题无关的代码。如果您可以硬编码对
insertbin()的调用并摆脱所有用户输入内容,这将很有帮助。 minimal reproducible example 越简单越好。 -
malloc使内存未初始化 stackoverflow.com/a/1538427/3365922 所以你可能有错误的z->sonleft和z->sonright -
我应该把它改成
calloc吗? -
calloc几乎适用于您可能会看到的任何实现,尽管从技术上讲,它不能保证初始化指向NULL的指针。
标签: c while-loop null