[英]N-ary trees in C
Which would be a neat implemenation of a N-ary tree in C language? 哪个是用C语言实现N-ary树的巧妙实现?
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: 特别是,我想实现一个n-ary树,而不是自我平衡,每个节点中有一个未绑定数量的子节点,其中每个节点都包含一个已定义的结构,例如:
struct task {
char command[MAX_LENGTH];
int required_time;
};
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. 任何n元树都可以表示为二叉树,其中每个节点中左指针指向第一个子节点,右指针指向下一个兄弟。
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. 该技术的优点在于许多算法更易于编写,因为它们可以在二叉树上表示,而不是在更复杂的数据结构上表达。
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 TreeNode s. 作为第一遍,您可以简单地创建一个包含任务的结构 (让我们称之为TreeNode ),以及一组指向TreeNode的指针。 This set could either be an array (if N is fixed) or a linked list (if N is variable). 该集可以是数组(如果N是固定的)或链表(如果N是可变的)。 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). 链表要求您使用指向实际子节点(树的一部分)的TreeNode指针和指向列表中下一个ListNode的指针来声明一个额外的结构 (让我们称之为ListNode )(如果在结尾处,则为null)列表)。
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.