递归函数中的奇怪返回行为

时间:2015-04-09 22:18:56

标签: c++ recursion tree

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

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');

2 个答案:

答案 0 :(得分:4)

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

(*it)->hasChild(_value);

这应解决您的问题(禁止其余代码出现任何问题)

答案 1 :(得分:3)

你的问题在于hasChild它自称的方式:

(*it)->hasChild(_value);

调用但不对返回值执行任何操作。您可能想尝试返回结果。

由于您的算法似乎表明了一个未排序的树,因此并不像使用return为语句添加前缀那么容易。您可能需要检查true并返回它,但false表示继续查看:

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

您还需要在函数末尾返回false。