Algorithm to print a tree in C++

Viewed 59

I am struggling to write the algorithm to accomplish the following (simple) task. Consider a tree like this:

A0 B0 C0 D0 E0
      |
      C1 D1 E1      (Note: C1 and C2 are childs of C0, whereas
      |                    D1 and D2 are childs of C1 and C2
      C2 D2                respectively)

Of course it is stored in a tree, where each node has a pointer to the parent and a vector of pointers to the childs (it is a multiway tree). Something like this:

struct Node {
  Data          m_data;
  Node*         m_prev;
  vector<Node*> m_next;
  void Print();
}

I would like to write an iterative Print function to write the tree like this:

A0 B0 C0  
  1: C1 D1 E1 
  2: C2 D2
D0 E0

The function could be something like this:

void Print(Node* node) {
  node->Print();  
  if (node->NumOfNext() == 1) {  // NumOfNext returns the size of m_next
    Print(node->Next(0));  // returns the first child       
  } else if (node->NumOfNext() > 1) {
    // ???
  }
}

However I fail in correctly navigate trough the childs in case of multiple childs. Any suggestions?

Thank you very much.

0 Answers
Related