Consider the following C program segment
struct CellNode{
struct CellNode *leftChild
int element;
struct CellNode *rightChild;
};
int Dosomething (struct CellNode *ptr)
{
int value = 0;
if(ptr != NULL)
{
if (ptr -> leftChild != NULL)
value = 1 + DoSomething (ptr -> leftChild);
if (ptr -> rightChild != NULL)
value = max(value, 1 + Dosomething (ptr -> rightChild));
}
return(value);
}
The value returned by the function when a pointer to the root of a non-empty tree is passed as argument is
View worked solution
Answer: D
Let us analyze the behavior of the function DoSomething(ptr) by tracing it on simple binary trees:
- Single-node tree (Root only):
Since both
leftChildandrightChildareNULL, the conditions inside theifblocks are false. The function returns the initial value, which is0. - Two-node tree (Root with one child):
For the root, the child is not
NULL. The function recursively calls itself on the child (which returns0) and setsvalue = 1 + 0 = 1. It returns1. - Three-node tree (Root with left and right children):
The left recursive call returns
0, settingvalue = 1 + 0 = 1. The right recursive call also returns0, and the function updatesvalue = max(1, 1 + 0) = 1. It returns1.
In general, for any node, the function computes . This is the standard recursive definition for the height of the tree (measured as the number of edges on the longest path from the root to a leaf).
Free practice · Your answers on this page are not saved.
