vector of struct Question

Hi, I am trying to figure out how to implement a print() function for this code.

test.h
1
2
3
4
5
6
7
8
9
10

private:
   struct node
   { 
     int data;
     node * left;
     node * next;
   };

   vector<node*> tree;


test.cpp
1
2
3
4
5
6
7
8
9
10
11

 void test::print()
{
  for(int i = 0; i < tree.size(); i++){
   cout << tree[i]->data << " ";
   //This causes problems when an index is NULL and I do not understand how to 
   // transverse the other pointer aka *left, * next to get the data.
  }

}
Last edited on
You do that by recursively printing the left and right child node.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void test::print()
{
  printRE(tree);
}

//The problem is I am not sure what to pass as the parameter vector<node *> head does not work for the recursion?
void test::printRe(vector<node*> head)
{
    for(int i = 0; i < head.size(); i++)
    {
          if(head[i] != NULL)
          {
              if(head[i]->left) printRe(head[i]->left);
              cout << " " head[i]->data << " " << endl;
              if(head[i]->next) printRe(head[i]->next);

           }
           else{
                     i = i+1;
            }

     }
}

The function should take a node, not a vector of nodes.
Then you call the function for each root node in "tree" - which is incorrectly named, by the way.
If each elements is a root node, it should be called "trees".
Last edited on
Topic archived. No new replies allowed.