我有以下可行的方法,但想知道是否有更好的方法。更好的意思是更有效和或更紧凑。
该功能检查一个Trie,以查看单词是否在Trie中。
bool check(const char *word)
{
int nodeIdx = hash(word);
if (nodeIdx < 0)return false;
nodeWords * searchNode;
searchNode = nodeArray[nodeIdx]; //nodeArray is global
bool whileFlag = true, returnFlag = false;
do
{
if (strcmp(word,searchNode->word) == 0 )
{
whileFlag = false;
returnFlag = true;
}
else if (strcmp(word,searchNode->word) < 0 )
{
if(searchNode->left == NULL)
{
whileFlag = false;
}else{
searchNode = searchNode->left;
}
}else{
if(searchNode->right == NULL)
{
whileFlag = false;
}else{
searchNode = searchNode->right;
}
}
}while (whileFlag);
free(searchNode);
return returnFlag;
}
例如,我们可以这样重写函数:
bool check(const char *word)
{
int nodeIdx = hash(word);
if (nodeIdx < 0)return false;
nodeWords * searchNode;
searchNode = nodeArray[nodeIdx];
bool returnFlag = false;
do
{
if (strcmp(word,searchNode->word) == 0 )returnFlag = true;
else if (strcmp(word,searchNode->word) < 0 && searchNode->left != NULL) searchNode = searchNode->left;
else if (strcmp(word,searchNode->word) > 0 && searchNode->right != NULL) searchNode = searchNode->right;
}while (searchNode->left != NULL || searchNode->right != NULL || strcmp(word,searchNode->word) == 0);
return returnFlag;
}