vendredi 8 mai 2015

Finding all parents from node to the root in a tree by recursion

I have a class Graph, modelling a Tree. Graph contain a pointer Graph* to the parent of my current instance (my current node).

class Graph
{
private:

    Graph*           parent;
public:
    Graph*           getparent();
}

Graph*          Graph::getparent()
{
    return this->parent;
}

parent is at nullptr if root.

I'm trying to find the distance from a node to the root, starting from the node.

Here is my try :

int Graph::howManyParents(Graph* unparent)
{
    int nbParents(0);
    if(unparent != nullptr)
    {
        nbParents++;
        nbParents =+ howManyParents(this->parent);
    }
    return nbParents;
}

It compiles but crashes. Debbugger show me lots of call to the method, but end up SegFaulting. Is there something wrong with my algorithm ?

Aucun commentaire:

Enregistrer un commentaire