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:

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

    ReplyDelete
  2. Problems and solutions are from:

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

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

    ReplyDelete
  4. Thanks for the info. It is very helpful.

    Regards
    Educational site

    Get jobs info at Educational site

    ReplyDelete
  5. 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;
    }
    }
    }
    }

    ReplyDelete