[英]How can I return the pointer to a specific node in this Binary Tree?
我有兩種方法(布爾值和指針返回值)用於在 C 中的二叉樹中搜索值:
bool findInTree(BTNode* bt, char* str) {
if (bt == NULL) {
return false;
}
if (strcmp(((Course*) (bt->data))->name, str) == 0) {
return true;
}
bool b1 = findInTree(bt->left, str);
if (b1) {
return true;
}
bool b2 = findInTree(bt->right, str);
return b2;
}
void* findAndReturnInTree(BTNode* bt, char* str) {
if (bt == NULL) {
return (void*) NULL;
}
if (strcmp(((Course*) (bt->data))->name, str) == 0) {
return bt->data;
}
void* b1 = findAndReturnInTree(bt->left, str);
if (strcmp(((Course*) (b1))->name, str) == 0) {
return b1;
}
void* b2 = findAndReturnInTree(bt->right, str);
return b2;
}
findInTree()
工作完全正常,並根據該值是否在樹中返回正確的布爾值。 但是, findAndReturnInTree()
不起作用,我不斷收到分段錯誤。 我試圖用findInTree()
對其進行建模,但返回一個指針而不是布爾值。 順便說一句,我使用void
指針作為->data
以便我可以使用多個結構並具有某種通用實現。 有人可以幫我解決這個問題嗎?
如果未找到樹節點, b1
、 b2
可能具有 NULL 值。
之后b1->name
可能是分段錯誤。
你為什么不在b1
, b2
添加檢查 NULL ?
C 程序員總是檢查異常情況。
void* findAndReturnInTree(BTNode* bt, char* str) {
if (bt == NULL) {
return (void*) NULL;
}
if (strcmp(((Course*) (bt->data))->name, str) == 0) {
return bt->data;
}
void* b1 = findAndReturnInTree(bt->left, str);
if (b1 == NULL) return findAndReturnInTree(bt->right, str);
if (strcmp(((Course*) (b1))->name, str) == 0) {
return b1;
}
void* b2 = findAndReturnInTree(bt->right, str);
return b2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.