Question 1 [5] with sample solutions
Suppose the definition of the node struct within a binary search tree is as shown below. Assume our typical binary search tree layout, i.e. smaller values go to the left.
struct node {
int id; // this is the sorting key for the tree
float data; // additional data value associated with the key
node *left, *right;
};
Implement a recursive solution for
the countFrequency function described below.
// The function takes a data value and a node pointer as parameters, // and returns a count of how many times that value appears in the // data fields of nodes in the subtree. int countFrequency(float d, node *t);
SAMPLE SOLUTION
int countFrequency(float d, node *t)
{
if (t == NULL) return 0;
int sum = countFrequency(d, t->left);
sum += countFrequency(d, t->right);
if (t->data == d) sum++;
return sum;
}
|