GATE CS 2023 · Asymptotic Analysis & Recurrences

MCQ · 2 marks · Problem PROG-DIVC-0169

Consider the C function foo and the following binary tree. The root holds 10; its left child holds 5 and its right child holds 11. Node 5 has left child 3 and right child 8. Node 11 has no left child and has right child 13. Nodes 3, 8 and 13 are leaves.
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. A
    3 8 5 13 11 10
  2. B
    3 5 8 10 11 13
  3. C
    3 8 16 13 24 50
  4. D
    3 16 8 50 24 13

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{\text{foo}(p) = \text{sum of the values in the subtree of } p,\ \text{printed in postorder}}\]foo prints a node's subtree sum after both of its children are done (left, right, then the node).Leaf 3 prints 3. Leaf 8 prints 8. Node 5 prints \(5+3+8=16\).Leaf 13 prints 13. Node 11 prints \(11+0+13=24\).Root 10 prints \(10+16+24=50\).Output: 3 8 16 13 24 50.Answer: C

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com