I’m trying to restore memory allocated in a tree by traversing the tree and deleting the memory as necessary. For example, suppose I have the following tree structure:
struct tree
{
int *value;
tree *left;
tree *right;
}
tree *root; //always points to the root of this tree
I know that we have to visit each value after every recursive call, delete it, then move to the next node (which can be left or right), but the recursive process seems very counter intuitive (particularly the part where we move to the left or move to the right).
I’m trying to follow the rule of “do something with the root, recursively call the left, then recursively call the right,” but the way the code functions is confusing to me. How can I preserve the invariant of root? If someone can perhaps explain the concept pictorially that would be great.
as you need the tree for traversal during delete the idea is to delete on return
a very important aspect on recursion is when to stop. i assume that a NULL pointer in your struct indicates that there is no subtree.
the strategy is now to go as deep as possible
if (t->left) del_tree(t->left);when we reach a NULL pointer on both, left and right we are stranded in a leaf. we now clean the leaf (deleting value) and return. on return
delete t->left;is executed, this node has nothing left on the left subtree and continues on its right subtree.here i found a nice image of the traversal
the problem of deleting a tree is divided into 3 parts. deleting the left subtree, deleting the right subtree and cleaning up self. the deleting of a subtree (left or right) is very much the same procedure as deleting the tree itself. so you use the same function, this is called recursion.
think of deleting a file system structure. you decide for the strategy to delete the ‘left’ folder structure first, then you delete the subtree ‘right’ and finally you delete the file ‘value’. when during the execution of this strategy you change into a folder (no matter whether left or right) you notice that the problem looks the same. so you apply this strategy again to any folder in the tree.
what happens is, that you change into the directory left repeatedly unless there is no more directory in the current one. you delete the file ‘value’. then you go back one folder and delete the folder named ‘left’. now you look for a folder named ‘right’, change into it, find no folders, delete file ‘value’ and return to the previous folder. you delete the now empty ‘right’ and finally delete the file ‘values as well. next is to do a further return (backtracking). and so on.
you cannot delete non empty folders during going deeper. you have to delete when retreating.