I am trying to implement the deletion function for a binary search tree in C, however I am running into problems.
I have the following structs for the tree and the nodes
typedef struct {
double value;
struct Node *parent;
struct Node *right_child;
struct Node *left_child;
} Node;
typedef struct {
struct Node *root;
} Tree;
I also have an in-order traversal function
void inOrderTraversalNode(Node *n) {
if (n != NULL) {
inOrderTraversalNode(n->left_child);
printf("%f\n", n->value);
inOrderTraversalNode(n->right_child);
}
}
A subtree minimum function
Node * minimum(Node *n) {
while (n->left_child != NULL) {
n = n->left_child;
}
return n;
}
and a transplant function
void transplant(Tree *t, Node *u, Node *v) {
Node *p = u->parent;
//replace u's parent's child pointer to v
if (p == NULL) {
t->root = v;
} else if (u == p->left_child) {
p->left_child = v;
} else {
p->right_child = v;
}
//set v's parent pointer to u's parent
if (v != NULL) {
v->parent = p;
}
}
And finally I have the delete function
void delete(Tree *t, Node *z) {
//if node z has no left subtree, replace z with right subtree and vice-versa.
if (z->left_child == NULL) {
transplant(t, z, z->right_child);
} else if (z->right_child == NULL) {
transplant(t, z, z->left_child);
} else {
Node *y = minimum(z->right_child);
if (y->parent != z) {
transplant(t, y, y->right_child);
Node *y_right_child = y->right_child;
y_right_child = z->right_child;
y_right_child->parent = y;
}
transplant(t, z, y);
Node *y_left_child = y->left_child;
y_left_child = z->left_child;
y_left_child->parent = y;
}
}
However when I run the following code in main
int main(void) {
Node n1;
Node n2;
Node n3;
Node n4;
Node n5;
Node n6;
Node n7;
Node n8;
n1.value = 4;
n1.parent = NULL;
n1.left_child = &n2;
n1.right_child = &n5;
n2.value = 2;
n2.parent = &n1;
n2.left_child = &n3;
n2.right_child = &n4;
n3.value = 1;
n3.parent = &n2;
n3.left_child = NULL;
n3.right_child = NULL;
n4.value = 3;
n4.parent = &n2;
n4.left_child = NULL;
n4.right_child = NULL;
n5.value = 6;
n5.parent = &n1;
n5.left_child = &n6;
n5.right_child = &n7;
n6.value = 5;
n6.parent = &n5;
n6.left_child = NULL;
n6.right_child = NULL;
n7.value = 7;
n7.parent = &n5;
n7.left_child = NULL;
n7.right_child = NULL;
Tree t;
t.root = &n1;
printf("In order traversal\n");
inOrderTraversalNode(t.root);
printf("Delete node\n");
delete(&t,&n1);
inOrderTraversalNode(t.root);
return EXIT_SUCCESS;
}
It returns 1,2,3,4,5,6,7
for the first traversal. But it returns 1,2,3,4,7
for the second traversal after deleting n5
which is incorrect because it misses the n6
node containing 5
. I do not understand why this is happening. I have inserted some print statements in the delete function and the n7
node is adding the n6
node as its left child, but for some reason it doesn't get printed during the traversal.