Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

struct - N-ary trees in C

Which would be a neat implemenation of a N-ary tree in C language?

Particulary, I want to implement an n-ary tree, not self-ballancing, with an unbound number of children in each node, in which each node holds an already defined struct, like this for example:

struct task {
  char command[MAX_LENGTH];
  int required_time;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Any n-ary tree can be represented as a binary tree where in each node the left pointer points to the first child and the right pointer points to the next brother.

             R                        R
           / |                       |
          B  C  D                     B -- C -- D
         /     |                     |         |
        E   F   G                     E -- F    G

So, your case would be:

struct task {
  char command[MAX_LENGTH];
  int required_time;
};

struct node {
  struct task taskinfo;
  struct node *firstchild;
  struct node *nextsibling;
};

This technique has the advantage that many algorithms are simpler to write as they can be expressed on a binary tree rather than on a more complicated data structure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...