【问题标题】:Deleting a full branch from n-ary tree从 n 叉树中删除一个完整的分支
【发布时间】:2018-05-09 01:24:43
【问题描述】:

我想让一个函数能够删除一个分支(甚至整个树)。树的结构如下:

typedef struct node {
    char data;
    struct node *child;
    struct node *sibling;
}*tree;

我创建了一个函数,它能够在树中找到给定数据,然后返回该节点的地址,然后将其删除。假设我想删除数据中包含B 的节点,它应该删除它的所有子节点和节点本身,然后我应该留下以下树:

      R                        R     
      |                        |     
      B _ C _ D      -->>      C _ D              
      |       |                    | 
      E _ F   G                    G 

我有以下函数,但它只对删除整个树有用,如果我用它来删除分支,我将留下指向已释放内存的指针。

void delete_branch(tree node){
    if(node != NULL)
    {
        delete_branch(node->child);
        delete_branch(node->sibling);
        free(node);
    }
}

我知道问题出在哪里,我只需要更新指针,使它们再次指向正确的位置,但我不知道如何处理涉及的递归函数。如果需要更多信息,请随时询问。

【问题讨论】:

    标签: c tree


    【解决方案1】:

    考虑到你想保留兄弟而不是删除它

    tree delete_branch(tree node) {
        tree new_child=NULL;
        if(node != NULL) {
            while(node->child!=NULL) { //the child will keep being replaced by his sibling
                node->child=delete_branch(node->child); // replace the child by his sibling until there is none
            }
            new_child=node->sibling; // before freeing the child keep his the pointer to his sibling 
            free(node);
        }
        return new_child; // the sibling will replace the deleted child in the parent reference
    }
    

    以及移除孩子时;

    parent->child=delete(parent->child);
    

    【讨论】:

    • 现在应该可以了。也许我应该在结构中添加一个指向父级的指针以使其更容易。
    • parent->child=delete(parent->child); 是什么意思?被删除的节点可以是某人的直接孩子,也可以是他兄弟的兄弟姐妹,所以我们可能需要处理不同的情况对吧?
    猜你喜欢
    • 2015-05-07
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多