A destructive function modifies a tree. For example, the following function replaces each item in a tree by its cube.
void cubeAll(Tree T)
{
if(T != NULL)
{
T->item = cube(T->item);
cubeAll(T->left);
cubeAll(T->right);
}
}
Note that T does not need to be passed by
reference to cubeAll
because cubeAll does not need to change the pointer T. It only changes the node to
which T points (and other nodes in subtrees). So cubeAll uses
call by pointer.
But some functions do need to use call by reference,
since they need to store a different pointer into a variable.
We will see some examples of that shortly.
The mirror image of a tree is defined in question 4. Write a definition of function flip(T ) that changes T into its mirror image. This is a destructive function. Answer
Why doesn't the parameter of flip in the preceding question need to be passed by reference? Answer
Write a definition of function destroy(T ), which deletes every node in tree T. Answer