34B. Destructive Functions on Trees

A destructive function modifies a tree. For example, the following function replaces each item in a tree by its cube.

  void cubeAll(Tree T)
  {
    if(T != NULL)
    {
      T->item = cube(T->item);
      cubeAll(T->left);
      cubeAll(T->right);
    }
  }
Note that T does not need to be passed by reference to cubeAll because cubeAll does not need to change the pointer T. It only changes the node to which T points (and other nodes in subtrees). So cubeAll uses call by pointer. But some functions do need to use call by reference, since they need to store a different pointer into a variable. We will see some examples of that shortly.


Exercises

  1. The mirror image of a tree is defined in question 4. Write a definition of function flip(T ) that changes T into its mirror image. This is a destructive function. Answer

  2. Why doesn't the parameter of flip in the preceding question need to be passed by reference? Answer

  3. Write a definition of function destroy(T ), which deletes every node in tree T. Answer