N-ary trees in C

后端 未结 2 1588
青春惊慌失措
青春惊慌失措 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:17

    As a first pass, you could simply create a struct (let's call it TreeNode) which holds a task, as well as a set of pointers to TreeNodes. This set could either be an array (if N is fixed) or a linked list (if N is variable). The linked list would require you to declare an additional struct (let's called it ListNode) with a TreeNode pointer to the actual child (part of the tree), and a pointer to the next ListNode in the list (null if at the end of the list).

    It might look something like this:

    struct task {
      char command[MAX_LENGTH];
      int required_time;
    };
    
    struct TreeNode;
    
    struct ListNode {
      struct TreeNode * child;
      struct ListNode * next;
    };
    
    struct TreeNode {
      struct task myTask;
      struct ListNode myChildList;
    };
    

提交回复
热议问题