Skip to content

Commit 1c795c5

Browse files
committed
WIP: finding correct case 3 deletion (with view to drying up with recursion if this works)
1 parent 15f7dcd commit 1c795c5

File tree

2 files changed

+24
-17
lines changed

2 files changed

+24
-17
lines changed

binary-tree

4.01 KB
Binary file not shown.

lib-binary-tree.c

+24-17
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,14 @@ void print_in_order(Node *parent)
1818
{
1919
if (parent->left != NULL)
2020
{
21+
printf("Going left\n");
2122
print_in_order(parent->left);
2223
}
24+
printf("a parent\n");
2325
printf(" %d\n", parent->data);
2426
if (parent->right != NULL)
2527
{
28+
printf("Going right\n");
2629
print_in_order(parent->right);
2730
}
2831
}
@@ -138,16 +141,17 @@ Node *get_target(Node *target_parent, int value)
138141
return target_parent->right;
139142
}
140143

141-
Node* find_leftmost_node(Node *node)
144+
// maybe return something that contains the successor and its parent
145+
Node* find_successor_node(Node *node, Node *parent)
142146
{
143147
if (node->left == NULL)
144148
{
145-
return node;
149+
return parent;
146150
}
147-
return find_leftmost_node(node->left);
151+
return find_successor_node(node->left, node);
148152
}
149153

150-
void delete (Node *root, int value)
154+
void delete (Node *root, int value)
151155
{
152156
Node *target_parent = find_parent(NULL, root, value);
153157

@@ -178,23 +182,26 @@ Node* find_leftmost_node(Node *node)
178182
}
179183

180184
// case 3
181-
Node *leftmost = find_leftmost_node(target->right);
185+
printf("FINDING SUCCESSOR\n");
186+
Node *successor_parent = find_successor_node(target->right, target);
187+
Node *successor = successor_parent->left;
182188
Node *temp = NULL;
183-
if (target->data < target_parent->data)
189+
// copy successor value to target
190+
target->data = successor->data;
191+
192+
// case 1 deletion
193+
if (successor->left == NULL && successor->right == NULL)
184194
{
185-
temp = target_parent->left;
186-
target_parent->left = leftmost;
195+
return delete_no_children(successor_parent, successor);
196+
}
187197

188-
target_parent->left->left = temp->left;
189-
target_parent->left->right = temp->right;
198+
// case 2 deletion
199+
if (successor->left != NULL && successor->right == NULL) // left child
200+
{
201+
return delete_one_child(successor_parent, successor, successor->left);
190202
}
191-
else
203+
else if (successor->left == NULL && successor->right != NULL) // right child
192204
{
193-
temp = target_parent->right;
194-
target_parent->right = leftmost;
195-
196-
target_parent->right->left = target->left;
197-
target_parent->right->right = target->right;
205+
return delete_one_child(successor_parent, successor, successor->right);
198206
}
199-
free(target);
200207
}

0 commit comments

Comments
 (0)