在C中重新分配二进制树状结构 [英] Deallocating binary-tree structure in C

查看:223
本文介绍了在C中重新分配二进制树状结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链表,我猜树是这个样子:  

I have a linked list, I guess a tree looks like this:

-> grandma
    -> dad
        -> me
        -> sister
            -> niece
        -> brother
    -> uncle
        -> cousin

和我有一个结构如下

struct Node{
    Node *parent;
    Node *next;
    Node *child;
}

我将如何释放该链表?
我的想法是做一个深度优先搜索和释放的每个节点?

How would I free that linked list?
My idea is to do a depth first search and deallocate each node?

推荐答案

您的DFS的想法是对的。这是dealocate二叉树记忆的好方法:

Recursive depth-search

Your idea of DFS is right. It is a good way to dealocate binary-tree memory:

remove(node):
    if node is null: return

    //else
    remove(left node)
    remove(right node)

    free(node)

迭代求解

<一个href="http://$c$cgolf.stackexchange.com/questions/478/free-a-binary-tree">http://$c$cgolf.stackexchange.com/questions/478/free-a-binary-tree
既然你不希望使用任何递归解决方案,那里你可以找到很好的描述迭代之一。

Iterative solution

http://codegolf.stackexchange.com/questions/478/free-a-binary-tree
Since you don't want to use any recursive solution, there you can find well-described iterative one.

这篇关于在C中重新分配二进制树状结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆