c - Difference between two recursive algorithms to delete a binary search tree -
i have question these 2 algorithms:
this works normally:
node* deletetree(node* root) { if(root != null) { deletetree(root->left); deletetree(root->right); deallocatenode(root); } return root=null; }
this nope:
void deletetree(node* root) { if(root != null) { deletetree(root->left); deletetree(root->right); deallocatenode(root); } root=null; }
why? need set root
null
node pointer after delete of bst not point memory not allocated. prefer second algorithm because recall of function more intuitive.
theoretically, 2 algorithms equivalent if use second algorithm , try print bst, program goes in loop.
when have node *root
, assign node = null
won't affect value in exterior. if want modify pointer value, you'll have pass double pointer.
something like:
void deletetree(node** root) { if(*root != null) { deletetree(&((*root)->left)); deletetree(&((*root)->right)); deallocatenode(*root); } *root = null; }
but don't think need assign node = null
since free it. so, can assign node = null
after call deletetree , won't need mess double pointer.
Comments
Post a Comment