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;
}
}[Figure: binary tree with root 10; left child 5 with children 3 and 8; right child 11 with right child 13.] 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 prints in post-order the subtree sums: 3, 8, then 5+3+8=16, then 13, then 11+13=24, and finally 10+16+24=50.