BST二叉树在C中删除值为= 0的叶子中的函数

时间:2014-12-07 22:12:16

标签: c tree binary-tree binary-search-tree

我正在尝试在C中创建一个能够从二叉树(BST)中删除(删除)所有叶子的函数,该函数作为参数传递,零值(0)并且返回结果将是已删除的叶子的数量。注意:不是值为0但是只有叶子的节点。例如图中的BST:

enter image description here

该函数将返回2(删除红色圆圈后的零)。

1 个答案:

答案 0 :(得分:3)

这是一个伪代码:

int delete_zero_leaves (node){
    int deleted
    delete_zero_leaves_aux (node, &deleted);
    return deleted
}

pointer delete_zero_leaves_aux (node, deleted){
    boolean is_leaf = true
    // if there is a child
    if (node->left != NULL){
            // passing deleted by reference
            node->left = delete_zero_leaves_aux (node->left, &deleted)
            is_leaf = false
    }
    // if there is a child on the right side
    if (node->right != NULL){
            // passing deleted by reference
            node->right = delete_zero_leaves_aux (node->right, &deleted)
            is_leaf = false
    }
    if (is_leaf AND node->value == 0){
        free(node)
        deleted += 1
        return NULL
    }
    return node
}

由于你说节点没有自己父亲的指针,你可以返回一个指针并设置父指针的值(左或右)。