Wednesday, August 15, 2007

Write a C program to delete a tree (i.e, free up its nodes)

Free up the nodes using Postorder traversal!.

5 comments:

Anonymous said...

clear(struct node* pNode)
{
if (pNode != NULL)
{
clear(pNode->left);
clear(pNode->right);
delete pNode;
}
}

Anonymous said...

Problems and solutions are from:

http://cslibrary.stanford.edu/110/BinaryTrees.html

Job Interview Tips said...

here c interview questions are useful for students...
nice article..thanks for the author...
can you send me more c puzzles..

Unknown said...

Thanks for the info. It is very helpful.

Regards
Educational site

Get jobs info at Educational site

Anonymous said...

For more challenge, do it iteratively :)

void DeleteTreeIter( TreeNode* root )
{
if( !root ) { return; }

TreeNode* curr = root;
Stack s;

while( !s.IsEmpty() || curr )
{
if( curr )
{
if( curr->Right )
{
s.Push( curr->Right );
}
s.Push( curr );
curr = curr->Left;
}
else
{
curr = s.Pop();
if( curr->Right == s.Peek() )
{
TreeNode* temp = s.pop();
s.Push( curr );
curr = temp;
}
else
{
delete curr;
curr = NULL;
}
}
}
}