C:如何为生成树释放内存?
我有一个只有父母和孩子的 n 元树结构。生成树本身只包含一个节点,即根节点。然后创建与其他节点或根链接的节点。每个节点(包括根)最多允许有 MAXCHILDREN 个子节点。 结构如下:
typedef struct node{
unsigned int id; //every node has different id
struct node* parent; //points to parent node
struct node* children[MAXCHILDREN]; //pointers to all children of this node
}node;
typedef struct spantree{
node root; //root node
}spantree;
视觉图片:
root
___O
/ / \
O O O
/ \
O O
创建树后,我想取消分配整个树,但我不确定该怎么做。我无法从根开始释放,因为那样树就会被破坏。所以我想我必须从叶子开始直到根部? 但这意味着我必须先找到最深的叶子,对吗?我对如何开始感到很困惑。
我不认为这是必要的,但为了保险起见,我每次需要创建一个新节点时都会使用以下内容:
node *newNode;
newNode=(node*)malloc(sizeof(node));
//then I modify it to my preferences
I have a n-ary tree structure with only parents and children. The spantree itself holds only one node, the root. Then there are created nodes which are linked with other nodes or the root. Each node(root included) are allowed to have up to MAXCHILDREN children nodes.
Here's the structure:
typedef struct node{
unsigned int id; //every node has different id
struct node* parent; //points to parent node
struct node* children[MAXCHILDREN]; //pointers to all children of this node
}node;
typedef struct spantree{
node root; //root node
}spantree;
Visual picture:
root
___O
/ / \
O O O
/ \
O O
After I have created my tree I want to deallocate the whole thing but I am unsure on which way to do it. I can't start deallocating from the root because then the tree will get broken. So I imagine that I have to start from the leaves and going up to the root?
But that means that I have to find the deepest leaves first, right? I feel quite confused on how to start.
I don't think it's neccesary but for insurance here's what I use everytime I need to make a new node:
node *newNode;
newNode=(node*)malloc(sizeof(node));
//then I modify it to my preferences
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要检查要释放的节点是否有子节点,如果有,请先释放它们。
You need to check if the node you're freeing has children, and free them first if it does.
递归遍历树,先调用递归函数,然后释放内存。
Recurse through the tree, call the recursive function first, then free memory.
你是对的,你需要使用你最喜欢的遍历函数来找到叶子,然后在释放父节点之前释放它们。一旦子节点被释放,您基本上就拥有了另一个可以释放的叶节点。
您需要使用递归。享受!
You're correct, you need to use your favorite traversal function to find the leaves, and then free those before freeing the parent nodes. Once the children have been freed, you basically have another leaf node that you can then free.
You'll need to use recursion. Enjoy!
您听说过有关后序遍历的事情吗?您可以使用相同的技术来删除所有节点。删除所有子项后,这会自动删除父项。
You heard anything about POST-ORDER Traversing? You use the same technique to delete all of the nodes. This automatically deletes the parents after all their children are deleted.