-2

I want to create a multi branch tree in c, can you guys please help me out.

Tree structure:

                  O
                 /|\
                / | \
               O  O  O
              /|\     \
             / | \     \
            O  O  O     O
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
yesaar
  • 1
  • 1
  • 2

3 Answers3

1

Most common approach is First-Child/Next-Sibling tree. It uses only 2 pointers to keep any number of children, not unlike linked list.

typedef struct node {
    struct node *child;
    struct node *next;
} node;
Agent_L
  • 4,960
  • 28
  • 30
0

Here is a basic tree structure:

typedef struct node {
    struct node *left;
    struct node *right;
    char *string;
} node;

You can easily extend it for more branches by holding an array of pointers to node instead of just left and right but it won't be that efficient.

Alexandru Cimpanu
  • 1,029
  • 2
  • 14
  • 38
0

If the number of child nodes is fixed, or has a maximum number, you can use a pointers array:

typedef struct node {
    struct nodes *childs[];
    char *string;
} node;

Or you can dynamically allocate it:

typedef struct node {
    struct nodes **childs;
    char *string;
} node;

This allows direct access to the childs.
Another option is to use linked list to hold the childs. This way you can add/remove as many as you'd like, but you lose the direct access.

Paza
  • 121
  • 1
  • 5