Thread: delete whole tree

  1. #1
    Registered User hankspears's Avatar
    Join Date
    Mar 2002
    Posts
    14

    delete whole tree

    I'm having a bit of bother deleting an entire tree. I can't seem to delete the root node and bcheck tells me I have leaks all over the place.
    We've been given the structs:

    typedef struct TNode {
    int value;
    struct TNode* left;
    struct TNode* right;
    }TNode;

    typedef struct TNode* Tree;

    and the prototype:

    void destroyTree(Tree t);

    Here's my code:
    Code:
    void destroyTree(Tree t)
    {
      if(t->left != NULL) {
        destroyTree(t->left);
         t->left = NULL;
         free(t->left);
      }
    
      if(t->right != NULL) {
        destroyTree(t->right);
        t->right = NULL;
        free(t->right);
      }
    
      /* I added this to remove the root node, but I don't think it helps */
      if(t->left == NULL && t->right == NULL) {
        t = NULL;
        free(t);
      }
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Perform a simple post order traversal, but insted of printing the contents of the leaf, free it:
    Code:
    void 
    destroy ( Tree t )
    {
      if ( t != NULL ) {
        destroy ( t->left );
        destroy ( t->right );
        free ( t );
      }
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Originally posted by Prelude
    Perform a simple post order traversal, but insted of printing the contents of the leaf, free it:
    Code:
    void 
    destroy ( Tree t )
    {
      if ( t != NULL ) {
        destroy ( t->left );
        destroy ( t->right );
        free ( t );
      }
    }
    -Prelude
    NULL <- NODE1 <-> NODE2 -> NULL

    Node1 calls destroy(right), Node2 calls destroy(Left), Node1 calls destoy(Right), Node2 calls destroy(Left) and so on, and so on.....

  4. #4
    Registered User hankspears's Avatar
    Join Date
    Mar 2002
    Posts
    14
    That's got rid of the leaks, thanks Prelude. I guess I was making it too complicated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Interpreter.c
    By moussa in forum C Programming
    Replies: 4
    Last Post: 05-28-2008, 05:59 PM
  2. BST delete again, but this time I think I'm close
    By tms43 in forum C++ Programming
    Replies: 9
    Last Post: 11-05-2006, 06:24 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. BST/Red and Black Tree
    By ghettoman in forum C++ Programming
    Replies: 0
    Last Post: 10-24-2001, 10:45 PM