在比较根和将要插入的值时遇到问题。
我正在尝试从txt文件中读取名称,并构建一个二叉树(按字母顺序比较)。
我看到的问题是root-> name和value-> name变得相同,这本不应该发生。
例如
如果txt文件中的名称为:
alex
brian
chris
首先,由于rootNode为NULL,所以插入函数应将其根名称更改为alex。 然后,它将新名称(brian)与根节点的名称(alex)进行比较。 然后将新节点(布莱恩)设置为rootNode(alex)的rightNode。但它似乎没有这样做。
我在做什么错? 我将如何解决这个问题?
谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct binaryTree{
char* name;
struct binaryTree* leftNode;
struct binaryTree* rightNode;
};
struct binaryTree* insert(struct binaryTree* root, struct binaryTree* value);
struct binaryTree* init(char* val);
int main() {
struct binaryTree* rootNode = NULL;
char name[100];
int numWords;
int searchNum;
int deleteNum;
struct binaryTree* tempNode;
FILE *fPtr;
if ((fPtr = fopen("in.txt", "r")) == NULL){
printf("Error. No File Found");
exit(1);
}
for(int i = 0; i < 3; i ++){
fscanf(fPtr, "%d", &numWords);
fscanf(fPtr, "%d", &searchNum);
fscanf(fPtr, "%d", &deleteNum);
}
printf("%d %d %d", numWords, searchNum, deleteNum);
for (int i = 0; i <numWords; i ++){
fscanf(fPtr, "%s", name);
tempNode = init(name);
rootNode = insert(rootNode, tempNode);
}
return 0;
}
struct binaryTree* insert(struct binaryTree* root, struct binaryTree* value){
if (root == NULL){
printf("value = %s\n",value->name);
return value;
}
else{
if(strcmp(root->name, value->name)>0){
if(root->rightNode != NULL){
printf("inserting right");
root->rightNode = insert(root->rightNode,value);
}
else{
root->rightNode = value;
}
}
else if(strcmp(root->name, value->name)<0){
printf("inserting left\n");
if(root->leftNode != NULL){
root->leftNode = insert(root->leftNode,value);
}
else{
root->leftNode = value;
}
}
else{
printf("the names are same");
}
return root;
}
}
struct binaryTree* init(char* val){
struct binaryTree* temp;
temp = (struct binaryTree*)malloc(sizeof(struct binaryTree));
temp->name = val;
temp->leftNode = NULL;
temp->rightNode = NULL;
return temp;
}