NUIMCrest CS211 - Algorithms and Data Structures II
Department of Computer Science, NUIM
Laboratory Sheet 8

For week beginning Monday 20 March 2000
T. Naughton, CS NUIM

In this laboratory you will learn to manipulate binary trees. There are two programs to write, Problems 8.1 and 8.2. Show a demonstrator a working solution to each problem to get a credit. When finished, start on the list of problems at the end of this lab sheet.

Note: Twenty minutes before the end of the lab, demonstrators will concentrate on correcting your solutions. They will not answer questions from this time.

Back to CS211 home


Lab Sheet 8

Because of their recursive structure, tree manipulation tasks are often most easily expressed as recursive algorithms. To get you used to recursive definitions, here are recursive algorithms for some methods you have already coded iteratively.


In order to implement an ordered binary tree to store integers, the following first steps must be taken.

  • Define a class BinTreeNode containing each node’s data and two pointers
  • Create a class OrdIntTree to maintain the tree (it will have a 'root' instead of a 'head')
  • Create a constructor and destructor for OrdIntTree and Get and Set methods for your root

    Problem 8.1 Implement these first three steps (above). If you understand linked lists it should be easy. If you have to ask for a demonstrator's help then you don't understand linked lists!

    Next, we can implement some basic methods. (You should have some practice drawing the pictures from the last lab.)

  • Delete the whole binary tree (recursively)
  • Recursively check if a given integer is in the tree
  • Recursively print out a list of the integers in the tree (printed list need not be in sorted order)

    To help you along, here is a recursive algorithm for the second one:
    bool OrdIntTree::Contains(BinTreeElement * current, int value){
      //if current is NULL (i.e. we've reached the end of a subtree) then return false
      //otherwise, if the current node contains the value then return true
      //otherwise, if it's in the left subtree or in the right subtree then return true
    }

    Problem 8.2 Implement these three methods (above). Call a demonstrator when you have finished all three.

    Of course, it will not be possible to test these methods until we are capable of adding nodes to a tree. When you are finished Problems 8.1 and 8.2, and got your two credits for this lab session, try Problem 8.3.

    Problem 8.3 Enhance your solution to Problem 8.2 with the following methods:

  • Recursively add an integer to OrdIntTree
  • Delete a given integer from the tree
  • Print out the tree structure with all elements in their correct positions (you may print out the tree sideways if you wish)

    End of Lab Sheet