You have the parts you need. This is mainly a matter of reordering them.
void removeLeaves(struct Tree* const T){ if(T->left!=NULL){ removeLeaves(T->left); T->left = NULL; } if(T->right!=NULL){ removeLeaves(T->right); T->right = NULL; } }
Note, however, const
. Your code can work without it, but it should not, because setting T = NULL
does not actually do anything, although it may be possible.
Update: @ PaulP.RO The answer is interesting, by the way. I prefer mine, but you can try both and see what suits.
By the way, make sure you don't need the free()
call somewhere out there to prevent a memory leak.
source share