StreakPeaked· Practice

ExamsGATETechnical

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?

  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

Correct answer: 3 8 5 13 11 10

Solution

The function recursively calculates the sum of values in the binary tree, printing the cumulative sum at each node after processing its left and right children. This results in the output reflecting the order of node processing and their respective sums.

Related GATE Technical questions

⚔️ Practice GATE Technical free + battle 1v1 →