我正在尝试在C中创建一个能够从二叉树(BST)中删除(删除)所有叶子的函数,该函数作为参数传递,零值(0)并且返回结果将是已删除的叶子的数量。注意:不是值为0但是只有叶子的节点。例如图中的BST:
该函数将返回2(删除红色圆圈后的零)。
答案 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
}
由于你说节点没有自己父亲的指针,你可以返回一个指针并设置父指针的值(左或右)。