struct tree {
char info;
struct tree* left;
struct tree* right;
};
typedef struct tree Tree;
Tree* address = NULL; // How to remove this global variable?
void nodeAddress (Tree* a, char v) {
if (a != NULL) {
nodeAddress(a->left, v);
if (a->info == v) address = a;
nodeAddress(a->right, v);
}
}
uj5u.com熱心網友回復:
只需使用return,除非您真的認為雙指標更清晰。
由于您沒有明確目標,因此很難舉一個很好的例子:
如果多個節點可以匹配
v,您的代碼將選擇最右邊的一個,但是如果我們可以假設只有一個節點可以匹配
v,或者任何匹配的節點都是一個好的結果,那么你可以優化一些不必要的遞回(當然,除非你知道你有理由通過在在所有情況下都是整棵樹)。
所以,這是一個更簡單的例子,假設找到的第一個匹配是好的:
struct tree {
char info;
struct tree * left;
struct tree * right;
};
struct tree * find_matching_node(struct tree * a, char v)
{
struct tree * found = NULL;
if (a != NULL)
{
if (a->info == v)
{
found = a;
}
if(found == NULL)
{
found = find_matching_node(a->left, v);
}
if(found == NULL)
{
found = find_matching_node(a->right, v);
}
}
return found;
}
但這是一個與您的示例完全相同的示例:
struct tree * find_matching_node(struct tree * a, char v)
{
struct tree * found = NULL;
struct tree * found_rightmost;
if (a != NULL)
{
if (a->info == v)
{
found = a;
}
if(found == NULL)
{
found = find_matching_node(a->left, v);
}
found_rightmost = find_matching_node(a->right, v);
if(found_rightmost != NULL)
{
return found_rightmost;
}
}
return found;
}
你當然可以做雙指標,這是一個較小的代碼更改:
void find_matching_node(struct tree * a, char v, struct tree * * found)
{
if (a != NULL) {
find_matching_node(a->left, v, found);
if (a->info == v) *found = a;
find_matching_node(a->right, v, found);
}
}
但是請注意,最后一個版本既保留了遞回到整個樹的低效率,又保留了如果有多個匹配項時預期的行為的模糊性。效率低下可以通過一個足夠強大的優化編譯器來解決,但是這種歧義將代碼鎖定為總是遞回到右半部分,以防萬一你打算在多個匹配的情況下獲得最正確的匹配。
uj5u.com熱心網友回復:
我同意上述觀點,您應該只使用return.
還要考慮對指標使用另一層抽象,這完全是個人選擇的問題。我個人發現這種型別的指標型別定義使代碼更簡潔:
struct tree;
typedef struct tree *Position;
typedef struct tree
{
char info;
Position left;
Position right;
} Tree;
uj5u.com熱心網友回復:
按照您的提示,我找到了解決方案。謝謝!這是代碼:
find_matching_node(Tree* a, char v, Tree** found) {
如果(一個!= NULL){
find_matching_node(a->left, v, found);
if (a->info == v) *found = a;
find_matching_node(a->right, v, found);
}
}
樹* find(Tree* a, char v) {
樹*找到= NULL;
如果(一個!= NULL){
if (a->info == v) {
found = a;
return found;
}
if(found == NULL) find_matching_node(a->left, v, &found);
if(found == NULL) find_matching_node(a->right, v, &found);
}
發現退貨;
}
無效的主要(){
樹* x = find(root, 'a');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/495655.html
上一篇:嵌套物件遞回問題
下一篇:遞回演算法的記憶問題
