@@ -18,11 +18,14 @@ void print_in_order(Node *parent)
18
18
{
19
19
if (parent -> left != NULL )
20
20
{
21
+ printf ("Going left\n" );
21
22
print_in_order (parent -> left );
22
23
}
24
+ printf ("a parent\n" );
23
25
printf (" %d\n" , parent -> data );
24
26
if (parent -> right != NULL )
25
27
{
28
+ printf ("Going right\n" );
26
29
print_in_order (parent -> right );
27
30
}
28
31
}
@@ -138,16 +141,17 @@ Node *get_target(Node *target_parent, int value)
138
141
return target_parent -> right ;
139
142
}
140
143
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 )
142
146
{
143
147
if (node -> left == NULL )
144
148
{
145
- return node ;
149
+ return parent ;
146
150
}
147
- return find_leftmost_node (node -> left );
151
+ return find_successor_node (node -> left , node );
148
152
}
149
153
150
- void delete (Node * root , int value )
154
+ void delete (Node * root , int value )
151
155
{
152
156
Node * target_parent = find_parent (NULL , root , value );
153
157
@@ -178,23 +182,26 @@ Node* find_leftmost_node(Node *node)
178
182
}
179
183
180
184
// 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 ;
182
188
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 )
184
194
{
185
- temp = target_parent -> left ;
186
- target_parent -> left = leftmost ;
195
+ return delete_no_children ( successor_parent , successor ) ;
196
+ }
187
197
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 );
190
202
}
191
- else
203
+ else if ( successor -> left == NULL && successor -> right != NULL ) // right child
192
204
{
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 );
198
206
}
199
- free (target );
200
207
}
0 commit comments