To delete a tree we must traverse all the nodes of the tree and delete them one by one. So which traversal we should use – Inorder or Preorder or Postorder.Answer is simple – Postorder, because before deleting the parent node we should delete its children nodes first。
/*
This function is same as deleteTree() in the previous program
*/
void _deleteTree(struct node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
_deleteTree(node->left);
_deleteTree(node->right);
/* then delete the node */
printf("\n Deleting node: %d", node->data);
free(node);
}
/* Deletes a tree and sets the root as NULL */
void deleteTree(struct node** node_ref)
{
_deleteTree(*node_ref);
*node_ref = NULL;
}