GATE / CS ARCHIVE

GATE CSE 2023 / QUESTION 47

GATE CSE 2023 Q47

Programming in C · Recursion · Full GATE CSE 2023 paper

GATE 2023, Q47 2 marks · MCQ
Report issue

Recursion

Question 47, GATE 2023: The binary tree has root 10, left child 5 with leaves 3,8, and right child 11 with right leaf 13. C function foo(NULL) returns 0; otherwise it evaluates retval=p->val+foo(p->left)+foo(p->right), prints retval, and returns retval. Find the output under the intended left-before-right evaluation, and explain the C-language caveat. Source options include C: 3 8 16 13 24 50.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C under left-before-right recursive evaluation; order not fixed by C

Each call returns its subtree sum and prints that sum after both child calls. The leaf sums are 3, 8, 13; the subtree rooted at 5 sums 16; that at 11 sums 24; the root sums 50. If the left recursive operand is evaluated before the right, the output is 3 8 16 13 24 50, official C. However C does not specify operand evaluation order for +. Evaluating the right subtree first can instead print13 24 3 8 16 50, and the two left leaves may also appear in either order. The printed order is therefore not portable as written; the final return value 50 is stable. Preserve the official answer with this missing evaluation-order assumption disclosed.

Teaching detail. For a node u, the return value obeys sum(u)=value(u)+sum(left)+sum(right), with sum(NULL)=0. The print is after both recursive returns, so children print their subtree totals before their parent prints. The left subtree total is 3+5+8=16; the right is 11+13=24; the root is 10+16+24=50. The parenthesization of additions does not impose an evaluation order on function-call operands in C. The key's ordering is therefore an intended traversal convention, not a portable consequence of the written expression.

Original paper, page 50 · Answer key