GATE 2023 CS – Question 47
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?

Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (C) 3 8 16 13 24 50
Explanation
`foo(p)` computes the sum of the subtree rooted at `p` and **prints it after both recursive calls** (post-order).
Tree: 10 has left child 5 (children 3 and 8) and right child 11 (right child 13).
- Leaf 3: prints 3. Leaf 8: prints 8.
- Node 5: $5+3+8=16$, prints 16.
- Leaf 13: prints 13. Node 11: $11+0+13=24$, prints 24.
- Root 10: $10+16+24=50$, prints 50.
Output: `3 8 16 13 24 50`: option (C).