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;
  }
}

[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?

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