33C. Nondestructive Functions on Trees

As for linked lists, we can separate functions on trees into nondestructive functions, which do not alter a tree, and destructive functions, which do.

Key rules to remember are:

  1. Every tree is either an empty tree or a nonempty tree. Consequently, most algorithms have a case for an empty tree and at least one case for a nonempty tree.

  2. Every nonempty binary tree has a left subtree and a right subtree. Algorithms on binary trees look at the left and right subtrees of a nonempty binary tree.

A simple nondestructive function is numNodes(T ), which yields the number of nodes in tree T. The algorithm breaks down naturally into two cases: an empty tree (NULL) and a nonempty tree.

  1. If T is empty then T has 0 nodes.

  2. If T  is nonempty then T  has its root (one node) plus all of the nodes in the left subtree plus all of the nodes in the right subtree.

Putting those ideas into a definition of numNodes(T ) yields the following.

  int numNodes(ConstTree T)
  {
    if(T == NULL)
    {
      return 0;
    }
    else
    {
      return 1 + numNodes(T->left) + numNodes(T->right);
    }
  }

Another example of a nondestructive function on trees is cubes(T ), which returns a tree that looks like T  except that each number is replaced by its cube. For example, if T is

then cubes(T ) yields the following tree, without modifying T.

  int cube(const int x)
  {
    return x*x*x;
  }

  Tree cubes(ConstTree T)
  {
    if(T == NULL)
    {
      return NULL;
    }
    else 
    {
      return new Node(cube(T->item), cubes(T->left), cubes(T->right));
    }
  }

Exercises

  1. Write a definition of function numLeaves(T ), which returns the number of leaves in tree T. Answer

  2. Write a definition of a function sum(T ) that returns the sum of all of the numbers in a given tree. If T is empty then sum(T ) is 0. Answer

  3. Write a definition of function nonneg(T ), which produces the tree that results by replacing each negative number in T by 0, and leaves nonnegative numbers as they were. For example, if T is the left-hand tree below then nonneg(T ) is the right-hand tree.

    This function must not modify T. The result tree should be made out of new nodes.

    Answer

  4. Write a definition of function mirror(T ), which produces a mirror image of tree T. To get the mirror image, imagine picking the tree up with a spatula and flipping it over. For example, the following two trees are mirror images of one another.

    This function must not modify T. The result tree should be made out of new nodes.

    Answer

  5. Read the definition of the height of a tree. Write a function height(T ) that returns the height of tree T. Answer