Consider the function and the binary tree shown.
typedef struct node {
int val;
struct node *left, *right;
} node;
int foo(node *p) {
int retval;
if (p == NULL)
return 0;
else {
retval = p->val + foo(p->left) + foo(p->right);
printf("%d ", retval);
return retval;
}
}

When is called with a pointer to the root node of the given binary tree, what will it print?
View worked solution
Answer: C
The function foo(p) performs a post-order traversal (Left Right Root) of the binary tree. For any node , it computes the sum of all node values in the subtree rooted at , prints this sum, and then returns it.
The binary tree structure is as follows:
- Root node:
- Left child of : (with left child and right child )
- Right child of : (with right child )
We trace the execution of foo post-order:
- foo(3): A leaf node. Prints , returns .
- foo(8): A leaf node. Prints , returns .
- foo(5): Prints , returns .
- foo(13): A leaf node. Prints , returns .
- foo(11): Prints , returns .
- foo(10): Prints , returns .
The printed sequence is: 3 8 16 13 24 50.
Free practice · Your answers on this page are not saved.
