【问题标题】:Strange return behaviour in recursive function递归函数中的奇怪返回行为
【发布时间】:2015-04-09 22:18:56
【问题描述】:

我有一个这样的树节点类:

class Node
{
public:
    Node();
    Node(char _value);
    ~Node();

    char getValue() const;
    Node* getParent() const;
    void addChild(Node* _child);
    bool isLeaf() const;
    bool isRoot() const;
    bool hasChild(char _value) const;
private:
    vector<Node*> children;
    char value;
    Node* parent;
};

我实现了一个 serach 方法:

bool Node::hasChild(char _value) const
{
    if (value == _value)
        return true;

    for (auto it = children.begin(); it != children.end(); it++)
    {
        if (*it != NULL)
        {
            (*it)->hasChild(_value);
        }
    }
}

但是,当我运行此代码时,tmp 变量始终为 false。如果我用调试器跟踪它,return true; 部分会执行,但递归会继续。有什么建议吗?

Node* root = new Node();
Node* a = new Node('a');
Node* c = new Node('c');

root->addChild(a);
root->addChild(c);

bool tmp = root->hasChild('a');

【问题讨论】:

  • 我希望任何好的编译器都会在到达非 void 函数的末尾时发出警告,而最后没有任何返回 - 表明问题的一部分。检查你是否这样做。

标签: c++ recursion tree


【解决方案1】:

您的hasChild 代码有两个主要缺陷,它永远无法返回false,并且您在以下行中对hasChild 的调用的返回值永远不会被使用:

(*it)->hasChild(_value);

这应该可以解决您的问题(排除其余代码的任何问题)

【讨论】:

    【解决方案2】:

    你的问题出在hasChild的自称方式上:

    (*it)->hasChild(_value);
    

    调用它,但不对返回值做任何事情。您可能想尝试返回结果。

    由于您的算法似乎表明了一个未排序的树,这并不像在语句前加上 return 那样简单。您可能需要检查 true 并返回它,但 false 意味着继续查找:

    if ((*it)->hasChild(_value))
        return true;
    

    你还需要在函数结束时返回 false。

    【讨论】:

    • 非常感谢,现在我看到了解决方案,很简单。对于将来偶然发现这个问题的任何人,这里是代码工作:pastebin.com/R37EEnwn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2018-11-13
    • 2021-10-17
    • 2016-11-06
    • 2016-11-07
    • 2013-07-23
    相关资源
    最近更新 更多