Skip to content
Official PYQ · 2023

GATE CS 2023 Q37 — Trees

Explain with AI

Consider the C\text{C} function foo\text{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\textsf{foo} is called with a pointer to the root node of the given binary tree, what will it print?

Choose one option
View worked solution

Answer: C

The function foo(p) performs a post-order traversal (Left →\rightarrow Right →\rightarrow Root) of the binary tree. For any node pp, it computes the sum of all node values in the subtree rooted at pp, prints this sum, and then returns it.

The binary tree structure is as follows:

  • Root node: 1010
  • Left child of 1010: 55 (with left child 33 and right child 88)
  • Right child of 1010: 1111 (with right child 1313)

We trace the execution of foo post-order:

  1. foo(3): A leaf node. Prints 3+0+0=33 + 0 + 0 = 3, returns 33.
  2. foo(8): A leaf node. Prints 8+0+0=88 + 0 + 0 = 8, returns 88.
  3. foo(5): Prints 5+foo(3)+foo(8)=5+3+8=165 + \text{foo}(3) + \text{foo}(8) = 5 + 3 + 8 = 16, returns 1616.
  4. foo(13): A leaf node. Prints 13+0+0=1313 + 0 + 0 = 13, returns 1313.
  5. foo(11): Prints 11+0+foo(13)=11+13=2411 + 0 + \text{foo}(13) = 11 + 13 = 24, returns 2424.
  6. foo(10): Prints 10+foo(5)+foo(11)=10+16+24=5010 + \text{foo}(5) + \text{foo}(11) = 10 + 16 + 24 = 50, returns 5050.

The printed sequence is: 3 8 16 13 24 50.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Trees questions