Delete a file tree if it is full using C
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?
Infinite loop? It should be access violation a.k.a SIGSEGV actually. When deleting leaf node, you just call delete(root)
but then you don't return. So the next two recursive deleteTree calls are still executed (thus causing SIGSEGV because root should be invalid). Either add return;
after delete(root)
or use this:
void deleteTree(struct tnode *root)
{
cout<<root->data<<endl;
if (root->lchild != NULL)
deleteTree(root->lchild);
if (root->rchild != NULL)
deleteTree(root->rchild);
delete(root);
}
it would also save one function call because of early child check.
You should probably be doing a post-order traversal that deletes the children and then deletes the root. Maybe:
void deleteTree(struct tnode *root)
{
if (root != NULL)
{
// ?? delete root->data ??
deleteTree(root->lchild);
deleteTree(root->rchild);
delete root;
}
}
If you prefer to avoid the recursive calls when the pointer is null, you can test each child for nullness before calling deleteTree()
recursively. Then you could conceivably replace the existing if
test with an assertion, though you'd have to worry about being asked to delete an empty tree (when the initial call to deleteTree()
is given a null pointer).
Hint: Should you really call deleteTree(root->lchild);
when there is no left child, or deleteTree(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 root
anymore (that it works for you is pure luck).
It should not be infinite loop but it is incorrect because the root->lchild may be null whilte the right children is not null when you deleteTree(root-lchild)
精彩评论