Write a C program to Delete a Tree.
I have written a small snippet of code to achieve this, but it goes into an infinite loop
void deleteTree(struct tnode *root)
{
cout<<root->data<<endl;
if( root->lchild == NULL && root->rchild == NULL)
delete(root);
deleteTree(root->lchild);
deleteTree(root->rchild);
//return root;
}
I want to delete it while traversing. I know that Post Order Traversal can be used. But some other idea can be there or not?
Hint: Should you really call
deleteTree(root->lchild);when there is no left child, ordeleteTree(root->rchild);when there is no right child? How do you think that this is related to the infinite recursion?Also: You should not delete the node first and then recurse into its children – because after the node has been deleted, it no longer exists, and you cannot really use
rootanymore (that it works for you is pure luck).