0
我的工作有前缀的实施中,在我试图构造如下插入和前缀搜索执行树
F-> R-> E->笔 - >(纬度经度+)
我已经实现了插入功能,它似乎工作。我通过打印出相应的纬度和经度值来验证这一点。
我遇到的问题是在我的搜索功能中,经度和纬度值返回(null)。此外,搜索功能对于一个单词也会返回true。
此刻我无法理解其中的根本问题是
插入函数
int trieInsert(struct trieNode *node, char *key, char *longitude, char *latitude){
struct trieNode *parent = node;
//printf("Longi: %s", longitude);
//printf(" ");
//printf("Latitude: %s \n", latitude);
if(key){
int index = 0;
int i = 0;
if(node){
while(key[i] != '\0'){
int indexVal = convertLetterToIndex(key[i]);
if(!parent->children[indexVal]){
parent->children[indexVal] = initializeTrie();
parent->children[indexVal]->value = key[i];
}
parent = parent->children[indexVal];
i++;
}
int longitudeLen = strlen(longitude);
int latitudeLen = strlen(latitude);
node->longi = malloc(longitudeLen + 1);
strncpy(node->longi, longitude, longitudeLen + 1);
node->longi[longitudeLen] = '\0';
//printf("Longi: %s", node->longi);
node->lat = malloc(latitudeLen + 1);
strncpy(node->lat, latitude, latitudeLen + 1);
node->lat[latitudeLen] = '\0';
//printf("Lati: %s \n", node->lat);
}
}
}
我搜索功能
bool getTrie(struct trieNode *root, char *key){
struct trieNode *pNode = root;
bool flag = true;
if(!key){
printf("Word is empty \n");
return false;
}
if(!root){
printf("Trie is empty \n");
return false;
}
int i = 0;
while(key[i] != '\0'){
int indexVal = convertLetterToIndex(key[i]);
if(!pNode->children[indexVal]){
printf("Character not found in trie \n");
flag = false;
break;
}
pNode = pNode->children[indexVal];
i++;
}
printf("Longitude: %s", pNode->longi);
printf(" ");
printf("Latitude: %s \n", pNode->lat);
return flag;
}
在我插入功能,纬度和经度值是否正确添加?
编辑
我的结构定义
struct trieNode{
char *longi;
char *lat;
struct trieNode *children[27];
char value;
};
如何定义'struct trieNode'? – purplepsycho
@purplepsycho我已将它添加到问题 – RRP
您的'printf(“Longitude:%s”,pNode-> longi);'如果pNode为NULL并且跳出循环,也会执行。而不是在循环内设置一个标志,你可以返回False。 – joop