Assignment #5

Programming

  1. First, implement the general Rooted Tree class as described in the grtree.h file below. You can put the missing implementations either in the grtree.h file, or in a separate grtree.cpp file and use an #include "grtree.cpp" at the end of grtree.h as the author does. Hint: To minimize typing and avoid errors, copy the code below to the clipboard and paste it into a text file and save as grtree.h. Or, download it from the course download area.
  2. Write a program using the GRTree class public member functions to do the preorder "tabbed" listing of the tree shown in Figure 4.5. Your results should look like Figure 4.7. Hint: Use the appropriate traversal scheme and the PrintValue(int ntabs) member function.
  3. Write a program using the GRTree class public member functions that prints Element: SubTreeSize for every node in the tree. SubTreeSize is the number of nodes in the subtree, including the node being reported. For example, the size of the subtree at cop3212 (Fig. 4.5) is 9. Hint: what traversal scheme is most appropriate?
// General Rooted Tree
// grtree.h
template <class Object>
class GRTree
{
protected:
Object Element;
GRTree *LMChild;
GRTree *RSibling;
//Public interface
public:
// Constructors
GRTree(): LMChild(NULL),RSibling(NULL), Parent(NULL){}
GRTree(const Object &element): Element(element), LMChild(NULL),
RSibling(NULL), Parent(NULL){} // Leaf
GRTree(const Object &element, GRTree * n1); // One child
GRTree(const Object &element, GRTree * n1, GRTree * n2); // Two children
GRTree(const Object &element, GRTree * n1, GRTree * n2, GRTree * n3); // Three children
virtual ~GRTree() {} // Destructor
// Public member functions
public:
GRTree *LeftMostChild(void){return LMChild;} // get leftmost child
GRTree *RightSibling(void){return RSibling;} // get leftmost child
void PrintValue() { cout << Element << " ";}; // print element
void PrintValue(int ntabs); // print ntabs tab chars, then Element.
Object Value() { return Element;}; // return Element
};

Pencil & Paper
(a) Discuss how you would implement a function GRTree * Parent(GRTree *root, GRTree *target) that returns a pointer to the parent of target in tree, without modifying the class GRTree in any way. Hint: You can traverse the tree using the class public member functions.
(b) Discuss another, more efficient implementation of this functionality but as a class member function GRTree * Parent( GRTree *target). Hint: Since you are modifying the class anyway, you might want to add more than just another public member function.

(c) In addition to describing the two different approaches, discuss their relative merits and shortcomings.

Note: "Discuss" means to provide a narrative using good English. You will be graded on English, depth, and content.