Points earned for these problems can be used to increase the
score of the second test. It is not possible to earn more than
the maximal number of points (which is 65 for test 2).
The declaration below is used for implementing binary trees
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 (3 points)
Write a templated 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.
template
int CountEqual(TNode * tree, const Kind & key)
// postcondition: returns # nodes in tree with info == key
{
}
Problem 2 (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 (6 points)
Two binary trees s and t are
equivalent if they
have the same shape; the values stored in the nodes do not affect
whether two trees are equivalent. In the diagram
below, the tree in the middle is NOT equivalent
to the other trees, but the tree on the right IS equivalent
to the tree on the left.
Write a function IsEquivalent that returns true if its two tree
parameters are equivalent and false otherwise. You must also give the
big-Oh running time of your function with a justification.