Name: ________________________________

Honor Code Acknowledgment: _____________________________


Random Quiz 8

CPS 100, Fall 1996

8 points

Due: November 14


Use the following definition of a node for a general tree in Problems 1 and 2.


struct Tree
{
   int info;
   Tree * child;  // pointer to leftmost child
   Tree * sib;    // pointer to sibling
};

Problem 1: How many children? (4 pts)

Write a function called NumChildren that returns the number of children of a node. For example, NumChildren(T) on the tree T in the figure shown below returns 3 (the number of children of the root), NumChildren(T->child->sib) on the tree T returns 4, and NumChildren(T->child->sib->sib->child) returns 1.

(Note the picture in the figure is different than the implementation. In the implementation, the root would have a child pointer to its leftmost child and a NULL sib pointer. The children of the root would be linked together by sib pointers. See the notes on trees.)

int NumChildren(Tree * T)
// postcondition: returns the number of children of T,
//                returns 0 if T is NULL or has no children

Problem 2: Maximum number of Children (4 pts)

Write a recursive function called MaxNumChildren that returns the maximum number of children over all nodes in the given tree. For example, MaxNumChildren(T) on the tree T in the figure shown above is 4 (there is one node with 4 children, the maximum number of children over all nodes), and MaxNumChildren(T->child->sib->sib) returns 2, the maximum number of children for a node in this subtree. Note that it doesn't matter if there is more than one node with the maximum number of children.

Complete the recursive function MaxNumChildren below. You may use the function NumChildren that you wrote in problem 1. Assume NumChildren works correctly, regardless of what you wrote above.

int MaxNumChildren(Tree * T)
// postcondition: returns the maximum number of children over all nodes
//                returns 0 if T is NULL or T has no children