I construct lots of object trees in my applications, where each node is your typical tree node (reference to parent and a list of references to children). These trees are temporary, meaning that I might dispose of them before application terminates.
So far I've always added a method to the tree node class which is able to recursively traverse a tree branch and "destroy it" (set parent reference to null and clear children list, etc.).
public void destroy() {
for (Node node : children) {
node.destroy();
}
parent = null;
children.clear();
}
This always made sense to me, since simply null-ing a reference to the root of the tree which you have stored somewhere is not enough - children might still have a reference to it, meaning that it will stay in memory and cause a memory leak. Am I correct in assuming this and providing such a method?
The reason why I'm doubting myself is that I rarely see such methods in APIs which provide tree structure support (at least not directly in tree node interfaces). What is the proper pattern for dealing with such cases?