[Solved] Free all elements in a tree [closed]


There are two ways you can do this, recursively or iteratively.

The recursive approach is the simplest to code. You write a “free node” function that checks if the node has any descendants or siblings and calls the “free node” on each of them, then it frees the node it was called on. Performing this “free node” operation on the root node will free the entire tree.

The iterative approach does the same thing but keeps a list of nodes to free. Here’s a sketch of the iterative approach:

  1. Create a list of pointers to nodes containing only the root node.
  2. Take the node at the head of the list, add all its siblings and direct children to the list of nodes, then free that node and remove it from the list.
  3. If the list is empty, stop, you are done.
  4. Go to step 2.

0

solved Free all elements in a tree [closed]