I have a hierarchical data that goes 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 TELEVISIONS. FLASH is the child of MP3 PLAYERS. MP3 PLAYERS, CD PLAYERS and 2 WAY RADIOS are the children of PORTABLE ELECTRONICS. You get the drill.
Now, I have a structure Node that contains its Id and its children, and so on, as to build a tree. Like this:
struct Node
{
int id;
list<Node*> children;
}
Each item is identified by an ID, which is the row number (ELECTRONICS=0, TELEVISIONS=1, and so on), so it is easy to find out who are the children of a node.
This is the tree I'm trying to build. This tree is not binary, as you can see. So applying recursion doesn't seem like an easy idea. Correct me if I'm wrong.
So how can I perform this? Help!
You should use pointers to Nodes instead, otherwise you will be duplicating data in your tree in each level.
I would also suggest you use an enum instead of int id, it makes the code a bit more clearer.
there is no problem using recursion with a non-binary tree, you just need to instead of calling left/right
(or similar) in your recursive function call each in the list<Node*>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With