Question
Consider the C function foo 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 foo is called with a pointer to the root node of the given binary tree, what will it print?
Official answer and solution
- Official answer
- C
- From
- Official GATE 2023 answer key
Solution
Perform a post-order traversal simulation of foo(p), computing subtree sums.
The function foo(p) recursively computes the sum of the subtree rooted at p:
It prints retval after both subtrees have returned (post-order fashion):
- Node 3 (leaf):
foo(3)returns . Prints:3 - Node 8 (leaf):
foo(8)returns . Prints:8 - Node 5 (left child of root): has children 3 and 8.
retval = 5 + 3 + 8 = 16. Prints:16 - Node 13 (leaf):
foo(13)returns . Prints:13 - Node 11 (right child of root): has right child 13 (left is NULL).
retval = 11 + 0 + 13 = 24. Prints:24 - Node 10 (root):
retval = 10 + 16 + 24 = 50. Prints:50
The complete printed sequence is: 3 8 16 13 24 50.
Option (C)
Printing node values (3 8 5 13 11 10) instead of the accumulated subtree sums.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2023 Computer Science and Information Technology (CS)
- Question
- 47 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.