Leaf removal does not affect BST-C

I wrote a function to invalidate all BST sheets. BST has a left and right pointer, and char has data to save the value of node.

void removeLeaves(struct Tree* T){ if(T->left == NULL && T->right == NULL){ printf("removing %c\n", T->data); T=NULL; } else{ if(T->left!=NULL){ removeLeaves(T->left); } if(T->right!=NULL){ removeLeaves(T->right); } } } 

I Print a tree before and after enabling this function. Although the above print statement works and prints zero nodes, the resulting tree is the same. I have something like:

 print(BST); removeLeaves(BST); print(BST); 

Any idea what is going on? Thanks.

+4
source share
3 answers

T=NULL; assigns null to a local pointer, not something in your tree. You need to use struct Tree ** so that you can modify struct Tree * :

 void removeLeaves(struct Tree ** T){ if((*T)->left == NULL && (*T)->right == NULL){ printf("removing %c\n", (*T)->data); *T = NULL; } else{ if((*T)->left!=NULL){ pruneTree((*T)->left); } if((*T)->right!=NULL){ pruneTree((*T)->right); } } } 
+1
source

You pass the value of T by value, so setting T to null does nothing (T is only a local copy of the pointer).

You need to somehow set T 'owner' (i.e. parent-> left or parent-> right) to null.

(Also, by setting the value of T to null, you risk a memory leak - do you need to free ()?)

+1
source

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.

0
source

Source: https://habr.com/ru/post/1415506/


All Articles