gpt4 book ai didi

c++ - 二叉树遍历 (MoSTLy) 失败

转载 作者:行者123 更新时间:2023-11-30 01:48:46 28 4
gpt4 key购买 nike

对于类(class),我必须创建一个州对象的二叉树,每个州对象都包含一个常驻对象的二叉树,用于组织居住在每个州的人。我正在尝试按名称在整个州树中搜索一个人(州树和居民树都是按名称的字母顺序排列的),这涉及遍历整个州树并在每个州的居民树中搜索该人。显然我的状态树遍历不起作用,因为大多数时候,当我知道他们确实存在时,它告诉我这个人不在数据库中(即我的树的 stateforperson 方法,如下所列,返回 NULL)在数据库中。我确定我的 searchfor() 方法有效。

node <Person*> * stateforperson (string nm, node <T> * n)
{ if (n != NULL)
{
node <Person*> * person = n->data->residents->searchfor(nm);
if (person != NULL)
return person;
return stateforperson(nm, n->left);
return stateforperson(nm, n->right);
}
else
return NULL;
}

尝试更新:

node <Person*> * stateforperson (string nm, node <T> * n)
{ if (n != NULL)
{
node <Person*> * person = n->data->residents->searchfor(nm);
if (person != NULL)
return person;
// Here, you explore the left branch and get the results.
node <Person*> * left_ret = stateforperson(nm, n->left);
// Here, same with right branch.
node <Person*> * right_ret = stateforperson(nm, n->right);
// You now have both results.
if (left_ret != NULL) // If a result was found in left branches, you return that person.
return left_ret;
else if (right_ret != NULL) // Same with right branch.
return right_ret;
else // The problem was here. Before you returned uninitialized memory. (because there wasn't a specified return value.
// Now, you return a NULL pointer if nothing was found.
//So you detect that no person was found and don't use unitialized memeory.
return (NULL);
}
else
return NULL;
}

最佳答案

我相信正在发生的事情是你只探索左边的节点。永远不要向右走,因为你早于返回:

     return stateforperson(nm, n->left); 
// Here you just return the left part. Never reaching the following line
return stateforperson(nm, n->right);

尝试实际存储值和类似的东西:

    left_ret = stateforperson(nm, n->left);
right_ret = stateforperson(nm, n->right);

比起对变量做任何需要做的检查以返回正确的变量。

(我相信这至少是问题所在。有一段时间没有进行任何递归编程,所以我可能会弄错。)

关于c++ - 二叉树遍历 (MoSTLy) 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29990818/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com