1

节点结构如下。

struct node
{
   int data;
   int noofchilds;
   node *child[n];
   node *parent;
 };

我会欣赏递归和非递归方法。

4

3 回答 3

1

非递归版本:

struct node {
    struct node *parent;
    unsigned nchild;
    struct node *child[XXX];
    int data;
    };

void deltree(struct node *np)
{
struct node *par;

while (np) {
        /* if this node has any children, start by
        ** "descending" to the highest numbered child and kill that first.
        */
        if (np->nchild--) {
                np = np->child[np->nchild];
                continue;
                }
        /* when we arrive here, *np has no more children left,
        ** so kill it, and step up to its parent
        */
        par = node->parent;
        // if np->child was obtained via malloc() uncomment next line
        // free (np->child);
        free (np);
        np = par;
        }
return;
}
于 2012-02-23T14:48:45.277 回答
0

删除节点并递归删除其子节点。

如果您必须删除完整的树(正如您的问题似乎是),则父指针无关紧要(并且随着节点本身的删除而被删除)。

于 2012-02-23T13:51:22.743 回答
0

迭代算法:

Start at the parent node.

Then do the following actions as long as possible:
   if the current node has one or more children: 
      set one of the children nodes as the (next) current node
   else
      delete the current node and use its parent as the (next) current node.
      if the current node was the root node (which has no parent), stop.
于 2012-02-23T14:05:55.747 回答