How to build a non-bounded tree with or without recursion?

I have hierarchical data that looks like this:

+----------------------+-------+
| name                 | depth |
+----------------------+-------+
| ELECTRONICS          |     0 |
| TELEVISIONS          |     1 |
| TUBE                 |     2 |
| LCD                  |     2 |
| PLASMA               |     2 |
| PORTABLE ELECTRONICS |     1 |
| MP3 PLAYERS          |     2 |
| FLASH                |     3 |
| CD PLAYERS           |     2 |
| 2 WAY RADIOS         |     2 |
+----------------------+-------+

TUBE, LCD and PLASMA are children of TVs. FLASH is the daughter of MP3 players. MP3 players, CD players and 2 WAY RADIOS are children of PORTABLE ELECTRONICS. You will get exercise.

Now I have a Node structure that contains its identifier and its children, etc., to build a tree. Like this:

struct Node
{
   int id;
   list<Node*> children;
}

Each element is identified by an identifier that is a line number (ELECTRONICS = 0, TELEVISIONS = 1, etc.), so it’s easy to find out who are the children of the node.

This is the tree I'm trying to build. This tree is not binary, as you can see. Therefore, using recursion does not seem like a simple idea. Correct me if I am wrong.

, ? !

+5
4

, .

int id, .

, left/right ( ) list<Node*>.

+4

, , . , .

, .. node . , . node, ( ) 0, node. , node.

0

Something like that:

int main()
{
    Node  flash(FLASH_ID);
    Node  mp3(MP3_ID);

    mp3.children.push_back(flash);
    // repeat
}
0
source

You can use more than one binding pointer. i.e.

struct node
{
int id;
node *first_child;
node *second child;
node *third_child;
}

In this case, the maximum is 3. You can specify nodes with different children and get access to them. In case there are less than 3 children, you can do it NULL.

0
source

All Articles