Custom tree handling

198 views Asked by At

I have to build a tree with a custom number of 'sons' in every node (dynamic table with pointers to the 'sons' of node) :

class node{
   public
   string data;
   int number_of_sons;
   struct node *father, **sons; // **sons is table of pointers to the "sons" of the node;

   node(string s, int n) : data(s), number_of_sons(n){   
   }//constructor

};

and the list class :

class tree{
   public:
   node *root;
   tree() : root(NULL){
   }
};

I create tree and nodes of the tree this way:

tree t1 = new tree();
node n1 = new node("example1", 1);
node n2 = new node("example2", 2);
node n3 = new node("example3", 1);
node n4 = new node("example4", 3);

And I am trying to insert them in "manually" way to the tree and this is not working :

n1->father = NULL;
t1->root = n1;

//adding the second object to the tree:
n2->father = root;
t1->root->sons[0] = n2;

Adding the "n1" to the empty tree works but the second operations is incorrect. Can someone give me an advice how to handle with this kind of tree? How to add a new node to the root?

2

There are 2 answers

2
eakgul On

You should allocate space for sons. You can use vector for sons or just can keep into array like: in constructor:

sons = new node[SIZE];
for(int i=0;i<SIZE;i++)
  sons[i]= new node();

then just code:

n1->father = NULL;
t1->root = n1;

//adding the second object to the tree:
n2->father = root;
t1->root->sons[0] = n2;
0
stamaimer On

I think n2 -> father = root is wrong. root is the data member of tree. you may refer it use t1 -> root. And if you want to define a tree, you just need to define a 'Node' class like this:

class Node
{
    string data_;
    std::vector<Node> children_;

public:
    Node(string);
} 

//

Node* root = new Node("root");
Node node = Node("child");
root -> children.insert(node);