【发布时间】:2015-05-01 16:21:58
【问题描述】:
对于类,我必须创建一个状态对象的二叉树,每个状态对象都包含一个常驻对象的二叉树,用于组织居住在每个状态中的人。我正在尝试按姓名搜索整个州的树(州和常驻树都按名称的字母顺序组织),这涉及遍历整个州树并在每个州的常驻树中搜索该人。显然,我的状态树遍历不起作用,因为大多数时候,当我知道他们确实存在时,它会告诉我该人不在数据库中(即我的 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;
}
【问题讨论】:
-
所以没有提供州名?你只需要搜索每个状态树?
-
是的。教授知道我知道如何寻找状态;现在他正在测试我们是否可以在树中搜索树,并处理不一定需要特定顺序的遍历。
标签: c++ tree binary-tree tree-traversal