338
LESSON 28 Making generic classes
EXERCISES
1. Finish building the generic Alternate method described earlier in this lesson. Add the code
needed to make the alternating version of the list. To make using the method easy, make it
static in the
ArrayMethods class. Make the main program test the method with lists containing
odd and even numbers of items.
2. Make the TreeNode class to represent a tree node associated with a piece of data of some
generic type. In addition to the code shown earlier in this lesson, give the class:
An
AddChild method that adds a new child node to the node for which the method
is invoked. Have the method take a piece of data of the class’s generic type as a
parameter and return a new
TreeNode representing that piece of data.
A private
AddToListPreorder method that adds a node’s subtree to a list in pre-
order format. The preorder format lists the node’s data first and then recursively
calls the method to add the data for the node’s children. You can use code similar
to the following:
// Recursively add our subtree to an existing list in preorder.
private void AddToListPreorder(List<TreeNode<T>> list)
{
// Add this node.
list.Add(this);
// Add the children.
foreach (TreeNode<T> child in Children)
{
child.AddToListPreorder(list);
}
}
A public
Preorder method that returns the node’s subtree items in a list in preorder
format. The method should call
AddToListPreorder to do all of the work. You can
use code similar to the following:
// Return a list containing our subtree in preorder.
public List<TreeNode<T>> Preorder()
{
List<TreeNode<T>> list = new List<TreeNode<T>>();
AddToListPreorder(list);
return list;
}
For extra credit, add similar methods to build lists in postorder and inorder. In
postorder, a node recursively adds its children to the list and then adds its own data.
In inorder, a node recursively adds the first half of its children to the list, then itself,
and then the rest of its children.
Make the main program build the tree shown in Figure 28-1, although it doesn’t need to dis-
play it graphically as in the figure. Make the program display the tree’s preorder, postorder,
and inorder representations as shown in Figure 28-2.
596906c28.indd 338 4/7/10 12:34:14 PM