Skip to main content

GATE CSE 2023Data Structures › Trees & Binary Search TreesVerified

GATE CSE 2023 PYQ: Consider the C \text{C} C function foo \text{foo} foo and the binary tree shown. typedef struct node { int…

Consider the C\text{C} function foo\text{foo} and the binary tree shown.

  1. typedef struct node {
  2. int val;
  3. struct node *left, *right;
  4. } node;
  5.  
  6. int foo(node *p) {
  7. int retval;
  8. if (p == NULL)
  9. return 0;
  10. else {
  11. retval = p->val + foo(p->left) + foo(p->right);
  12. printf("%d ", retval);
  13. return retval;
  14. }
  15. }

GATE CSE 2023 Trees & Binary Search Trees diagram: Consider the C \text{C} C function foo \text{foo} foo and th

When foo\textsf{foo} is called with a pointer to the root node of the given binary tree, what will it print?

  1. A
    3  8  5  13  11  103 \;8 \;5 \;13 \;11\; 10
  2. B
    3  5  8  10  11  133 \;5\; 8\; 10\; 11\; 13
  3. C
    3  8  16  13  24  503 \;8 \;16 \;13\; 24\; 50
    Correct answer
  4. D
    3  16  8  50  24  133\; 16\; 8\; 50\; 24\; 13

Answer

(C) 3 8 16 13 24 50 3 \;8 \;16 \;13\; 24\; 50 3 8 16 13 24 50

Approach

The function foo prints the sum of all values in the subtree rooted at p, but only after both children have been processed. Thus it performs a post-order traversal: leaves print their own values, internal nodes print their own value plus the already-computed child subtree sums. Compute subtree sums bottom-up and match against the options.

The recursion computes and prints subtree sums in post-order. The computed sums are 3, 8, 16, 13, 24, 50, which is exactly option C.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.