c - 找到时无法返回树节点
问题描述
找到树节点后如何返回它?
所以,我有一棵二叉树,当我在树中搜索我搜索的内容时,我想返回指向该节点的指针,这样我就可以在其他函数中使用该节点。有我的搜索功能:
Tnode *Tsearch(Tnode *r, char *word) {
if(r == NULL) {
printf("%s NOT FOUND\n", word);
return NULL;
}
int comp = strcasecmp(r->word, word);
if( comp == 0) {
printf("%s FOUND\n", r->word);
return r;
}
else if( comp > 0) {
Tsearch(r->left, word);
}
else if( comp < 0) {
Tsearch(r->right, word);
}
return 0;
}
我的问题是,当我尝试使用函数 Tsearch 的返回时它不起作用,我真的不明白为什么以及如何解决它。
我想使用从搜索函数返回的节点的函数如下:
int Tsearch_ref(Tnode *r, char (*words)[30]) {
if(r == NULL) {
return 0;
}
printf("%s, %d", words[0], (int)strlen(words[0]));
Tsearch(r,words[0]);
auxT = Tsearch(r,words[0]);
Lnode *aux = auxT->head;
printf("Title: %s\n", ((Book *)aux->ref)->title);
while(aux != NULL) {
aux_arr[i].ref=aux->ref;
printf("Title: %s\n", ((Book *)aux_arr[i].ref)->title);
printf("%p\n", &(aux_arr[i].ref));
aux = aux->next;
i++;
}
}
这个函数不完整,因为我试图解决返回问题,但基本上我想把里面有一个列表的树节点放在一个临时数组中。
结构如下:
typedef struct {
char *title;
char isbn13[ISBN13_SIZE];
char *authors;
char *publisher;
int year;
} Book;
typedef struct lnode {
struct lnode *next;
void *ref;
} Lnode;
typedef struct tnode {
struct tnode *left;
struct tnode *right;
char *word;
Lnode *head;
} Tnode;
这是我在 StackOverflow 中的第一个问题,所以如果您需要任何有关任何内容的更多信息,我显然会提供。
提前致谢!
解决方案
您需要更改对 Tsearch 的递归调用以实际返回找到的节点。所以,而不是这段代码:
else if( comp > 0) {
Tsearch(r->left, word);
}
else if( comp < 0) {
Tsearch(r->right, word);
}
做这个:
else if( comp > 0) {
return Tsearch(r->left, word);
}
else if( comp < 0) {
return Tsearch(r->right, word);
}
请注意,如果您的树非常深,您可能会用完整个调用堆栈并抛出异常。
推荐阅读
- python - 获取 TypeError:“NoneType”类型的对象在 Python 上没有 len()
- php - 卷曲请求狂饮
- java - 从 maven 中央存储库中删除 Azure blob 存储 12.5.0 依赖项
- amazon-web-services - AWS Cognito:在 AdminLinkProviderForUser 之后主账户上的电子邮件未经验证
- swiftui - 无法在 ListView SwiftUI 中使用按钮工作表
- javascript - 用于高图位置的自定义 SVG 符号
- python - 如何使用不同数量的 python 值编写 CSV
- c++ - c++中幂函数的奇怪行为
- java - 不同模块的版本 gradle
- javascript - 在javascript中将多个二维数组合并为一个二维数组