我正在尝试为学校项目构建三元搜索树。据我所知,我的代码看起来还不错。
但是,当我使用 malloc 时,原始根函数的叶节点没有被初始化。因此,除了第一个字符串比较(无论根的字符串是什么)之外的每个字符串比较都会为空(不是 null,而是“”)。我没有将任何指针作为函数参数传递,所以我无法弄清楚问题所在。请帮忙!
我怀疑问题出在这部分代码中。我真的绞尽脑汁搜索并无法弄清楚我的问题是什么。
如果您愿意,可以使用更多代码。
我已经检查并且 root->right 指向一个完全不同的位置,而不是第一次通过时 current->right 。那是我真正的问题。我认为这一定是声明中的错误之类的,但我就是想不通。
node_t* buildTree(FILE *file)
{
// check for at least one input
// set this input as the root of the tree
// if there is no input, print error message and return
char start[MAX_TOKEN_LENGTH];
fscanf(file, "%s", start);
printf("Root: %s\n", start);
node_t *root = malloc(sizeof(node_t));
root->counter = 1;
root->depth = 0;
root->right = NULL;
root->middle = NULL;
root->left = NULL;
printf("Allocated.\n");
int n = 0;
while(n < strlen(start))
{
root->string[n] = start[n];
n++;
}
printf("Root stored as: %s\n", root->string);
char word[MAX_TOKEN_LENGTH];
while(fscanf(file, "%s", word) != EOF)
{
printf("Read a word: %s\n", word);
// Reset depth and sort location
// Start sorting from the root element
int depth = 0;
node_t *current = root;
// Continue sorting into the tree until a null node is encountered.
// Increment the depth each pass
while (current->string != NULL)
{
printf("Comparing %s with %s, result is %d\n", word, current->string, strcmp(word, current->string));
if ( ( word[0] == current->string[0] ) && ( strcmp (word, current->string) != 0 ) )
{
printf("Middle node\n");
if (current->middle == NULL)
{
printf("Middle node is empty; creating new leaf.\n");
current->middle = malloc(sizeof(node_t));
int n = 0;
while (n < strlen(word))
{
current->middle->string[n] = word[n];
n++;
}
current->middle->counter = 0;
current->middle->depth = ++depth;
current->middle->left = NULL;
current->middle->middle = NULL;
current->middle->right = NULL;
break;
}