我想在二叉搜索树中搜索一个单词。这是我的代码。但它有运行时错误。
struct node {
int id;
char text[100];
strcut node *right;
struct node *left;
}
int main(){
// reading fles from the folder. The folder's name is Texts .
if(( dir = opendir("C:\\Texts\\")) != NULL ){
while((ent = readdir(dir)) != NULL ){
char k[100],l[100],*w;
char b[100];
char a[100]="C:\\Texts\\";
strcpy(b,folder->d_name);
file=fopen((strcat(a,b)),"r");
while(!feof(file)){
fgets(l,sizeof(l),file);
printf("%s",l); }
}
void listWord(node *tree,char word[]){
node * g, * h;
g=tree;
if(g==NULL ){
printf("list is empty");
}
else{
while(g!=NULL){
if(strstr(g->text,word)!=NULL){
printf(" specific word %s: \n",word);
printf("\n\t\t id is :%d ",g->id);
}
listWord(g->left,word);
listWord(g->right,word);
}
}
它不起作用:/我该如何解决? P.S:用户给出了单词,结构节点树有左,右,id,文本。
答案 0 :(得分:0)
你必须走遍整棵树,因为你没有按id
搜索,但你似乎已经意识到了这一点。要使用递归顺序遍历树,递归调用左子树上的函数,处理当前节点,然后递归调用右子树上的函数(适当地检查NULL)。例如:
void listWord(node *tree, char *word)
{
if (tree) {
/* If tree is not NULL... */
/* recursively process left subtree if present.. */
if (tree->left)
listWord(tree->left, word);
/* then check the current node.. */
if (strstr(tree->text, word)) {
printf(" specific word %s: \n", word);
printf("\n\t\t id is :%d ", tree->id);
}
/* then recursively process the right subtree if present. */
if (tree->right)
listWord(tree->right, word);
} else
printf("list is empty");
}