c++ - Strange return behaviour in recursive function -
i have tree node class this:
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; };
and have serach method implemented:
bool node::haschild(char _value) const { if (value == _value) return true; (auto = children.begin(); != children.end(); it++) { if (*it != null) { (*it)->haschild(_value); } } }
however, when run code, tmp variable false. if trace debugger, return true;
part executes, recursion continues. tips?
node* root = new node(); node* = new node('a'); node* c = new node('c'); root->addchild(a); root->addchild(c); bool tmp = root->haschild('a');
your problem lies in haschild
in way calls itself:
(*it)->haschild(_value);
you call not return value. may want try returning result.
since appears algorithm indicates non-sorted tree, that's not easy prefixing statement return
. need check true , return false means keep looking:
if ((*it)->haschild(_value)) return true;
you need return false @ end of function.