The GATE Grind

GATE 2023 CS – Question 47

Programming and Data Structures · Trees and Binary Search Trees · 2 marks · Multiple choice

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?

Diagram for GATE 2023 CS question 47
  1. 3 8 5 13 11 10
  2. 3 5 8 10 11 13
  3. 3 8 16 13 24 50
  4. 3 16 8 50 24 13

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).

Output: `3 8 16 13 24 50`: option (C).

More Trees and Binary Search Trees questions

All Trees and Binary Search Trees questions →