Name: ________________________________
Honor Code Acknowledgment: ___________________
Random Quiz # 6
CPS 100, Spring 1997
Due: February 17 (this quiz is guaranteed mandatory)
The declaration below is used for implementing binary trees, note
that it's templated which permits implementation of trees storing
any kind of info field.
template
struct TNode // "standard binary tree declaration"
{
Kind info;
TNode * left;
TNode * right;
TNode (const Kind & val, TNode * lchild = 0, TNode * rchild = 0)
: info(val),
left(lchild),
right(rchild)
{}
};
Problem 1: Count Chocula (3 points)
Write the function CountEqual that returns
the number of nodes with info field equal to key.
For the tree diagrammed below on the left the call
CountEqual(tree,3) should evaluate to 2 and
the call CountEqual(tree,6) should evaluate to 1;
for the tree on the right the call CountEqual(tree,6) should
evaluate to 2.
int CountEqual(TNode * tree, int key)
// postcondition: returns # nodes in tree with info == key
{
}
Problem 2: Mutate/ettauM (4 points)
Write a funtion Mutate that will add nodes to a tree. For all
parent-child node pairs with the same info field value, a new node
should be added between the parent node and child node with a value one
less than the info field value of the parent/child node. The tree on
the left above will be changed into the tree on the right as a result
of the call Mutate(tree).
void Mutate(TNode * tree)
{
}
Problem 3: Some Paths are More Equal than Others (4 points)
Write the function HasPathSum whose header is given below.
HasPathSum returns true if there exists some root-to-leaf path in
the tree whose root is t whose
nodes sum to target and returns false otherwise.
bool HasPathSum(Tree * t, int target)
// postcondition: returns true if there exists a path sum in t
// that sums to target (returns false if t == 0)
For example, in the tree shown below there are exactly four root-to-leaf
paths. The sums of the paths are 27, 22, 26, and 18. Thus the value
of HasPathSum(t,27) should be true and the value of
HasPathSum(t,30) should be false
(assuming t points to the
root of the tree --- the node whose info field has value 5.)
Owen L. Astrachan
Last modified: Fri Feb 14 11:36:45 EST