Is this a good way to recursively explore a tree structure?

Hi

I have objects in a tree data structure and need a function to explore an object's parents/grandparents. I've written the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

void findEntsAtLevel(EntityID id, PairIdUnitsVec& pairvec) //pairvec is passed by reference as it captures all parents/grandparents etc
{
  PairIdUnitsVec prts_v = getParents(id); //gets a vector of an objects immediate parents

  if (prts_v.size() <= 0) //no parents for this ent so go back (this ent will have been captured in the calling function)
  {
    return;
  }

  for (PairIdUnits prt : prts_v) //iterate over each parent and call function recursively
  {
      pairvec.push_back(prt);
    
      findEntsAtLevel(prt.related_ent_id, pairvec);
  }
}


This seems to work but I'd be grateful for any thoughts e.g. is passing the vector by reference good practice or should I try to be returning values (if that is possible here).

Thanks
A tree can have many children for each parent, but a child never has more than one parent.

https://en.wikipedia.org/wiki/Tree_%28data_structure%29

What your describing isn't a tree, or it is a tree but you've reversed the terms parents/children. Can you describe your data structure a little better?

I think for what you're describing, I would make a function in my Node class like this (pseudocode)

1
2
3
4
5
6
Node::enumerateParents(depth, function)
{
    if depth is 0:
        do function()
    else for each parent of *this, do enumerateParents(depth-1, function)
}
Last edited on
Topic archived. No new replies allowed.