0

I'm writing the class for the N-ary tree and I need to finish it with a destructor. For my tree, all I do is insert, traverse, print, and destruct it basically. The part of the code dealing with it will be something like:

while (/*not at end of input*/)
{ Tree now;
  // insert into tree
  // print 
}

It would be vital to have a destructor in this case right cause it dies when it hits the closing bracket. Right?

In most examples I've seen, most people just write something like, delete root; and leave it at that. I was under the impression that was a poor way to handle it cause all the other stored nodes are still there, you just can't reach them.

So, is that the best way to handle it or should I write some kind of function that clears each node until only contains the root and then delete it?

3
Contributors
3
Replies
5
Views
8 Years
Discussion Span
Last Post by DemonGal711
0

You have to delete all the branches of the tree you've allocated. You use delete to get rid of a single block of data. And delete[] - to get rid of an array of data. And if you just delete[] the root, the other branches would remain there.

Maybe you could try to use one of the STL containers. I've read there is a garbage collection library for C/C++ you should check that out. But I've never used it, so I have no experience with that kind of stuff.

http://developers.sun.com/solaris/articles/libgc.html
http://www.codeproject.com/KB/cpp/agm_libgc.aspx
The second link states, there are some drawbacks of using libgc...

0

If every node was created via new Node construct, that's a Node destructor stub is:

class Node
{
public:
    ...
    ~Node() {
        for (all_branches) // pseudocode!
            delete ith_branch_ptr;
        // this node destruction
        // code (if any)...
    }
    ....
};

Now if the root is a pointer to the tree root node (or 0 for an empty tree), you can delete the tree by

delete root;
root = 0;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.