我一直在头上撞墙几个小时了。我不知道该怎么做。我已经对函数进行了多次重组,但仍然没有使其正常工作。
这是我的c ++类中的编程任务。它必须具有特定格式,例如讲师给定的数据类型,参数等,因此我无法更改此类内容。我们必须使用字符数组,因此必须使用strcmp()。我们必须返回该人(如果找到),否则返回NULL。
到目前为止,我正在使用以下方法:
person *classname::getPersonByName(char *name, person *rt)
{
if (rt != NULL)
{
if (strcmp(rt->Title, title) == 0)
{
return rt;
}
else
{
getPersonByName(title, rt->left);
getPersonByName(title, rt->right);
//return NULL;
}
}
}
在调试中,它将按名称查找并返回该人员。问题在于,这将立即覆盖我的退货,因此最终不会找到正确的正确人。
被注释掉的底部的NULL最终将每次调用都设置为NULL,而不管搜索是否找到它。
最佳答案
问题是,您没有从递归调用中返回任何内容。
实际上,这个想法并不难,只需翻译以下伪代码即可:
// This is mostly a procedural way from your method signature, though you are using C++...
Node getPersonByName(Node node, String name) {
if (node is null) {
return null
}
if (node.name == name) {
return Node
}
Node result = getPersonByName(node.left, name);
if (result is not null) { // found in node.left
return result;
}
result = getPersonByName(node.right, name);
if (result is not null) { // found in node.right
return result;
}
return null;
}
我将把它留作功课,以便您将其转换为C / C ++,并通过避免多个返回点来使结构看起来更好
关于c++ - 按名称遍历树C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11751646/