当前我试图将我的文件中的每个单独的行存储到一个字符串中,然后将其存储在二叉搜索树中,但会出现问题。出于某种原因,当我打印我的BST时,只输出最后一行,而不是前三行。下面是我的代码。使用fgets读取文件中的行到二叉搜索树
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int count;
char* key;
struct node* left;
struct node* right;
};
struct node *newNode(char* item)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = NULL;
temp->right = NULL;
temp->count = 1;
return temp;
};
void printInorder(struct node* root)
{
if(root != NULL)
{
printInorder(root->left);
printf("%s \n", root->key);
printInorder(root->right);
}
}
struct node* insert(struct node* node, char* key)
{
if(node == NULL)//When tree is empty
return newNode(key);
if(strcmp(key, node->key) < 0)
node->left = insert(node->left, key);
if(strcmp(key, node->key) > 0)
node->right = insert(node->right, key);
return node;
};
int main()
{
struct node *root = NULL;
int i = 0;
char str[100];
FILE* fp;
fp = fopen("textFile.txt", "r");
if ((fp = fopen("textFile.txt","r")) == NULL)
{
printf("Could not open textFile.txt\n");
exit(1);
}
while(fgets(str, 100, fp) != NULL)
{
++i;
root = insert(root, str);
printf("%3d: %s", i, str);
}
printf("bst printed\n");
printInorder(root);
return 0;
}
TextFile.txt的包含
bob is working.
david is a new hire.
alice is bob's boss.
charles doesn't like bob.
而当BST被印刷,其输出是最后一个 查尔斯不喜欢鲍勃唯一线。
任何帮助真的不胜感激。
非常感谢您的帮助,我非常感谢您付出的努力,不仅为我解决问题,还一步一步解释我的代码中发生了什么,以便我能更好地理解它。非常感谢! – Kevag6