N-ary trees in C

后端 未结 2 1581
青春惊慌失措
青春惊慌失措 2020-12-13 02:39

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 chi

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 03:24

    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.

提交回复
热议问题