edited by
6,777 views
8 votes
8 votes

Consider the $\text{C}$ function $\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 $\textsf{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$
edited by

2 Answers

5 votes
5 votes

Given that retval = p → val + foo(p → left) + foo(p → right)

Means it will print the sum of ( value + leftsubtree whole value + right subtree whole value ).

Note that, until the child nodes completes the calculation, parent node calculation step will not complete.

 

Therefore leaf nodes returns the value of leaf nodes alone. ( 3 node, 8 node and 13 node will return 3, 8 and 13 respectively )

5 node will return 5+3+8 = 16

11 node will return 11+13 = 24

10 node will return 10+16+24 = 50

 

So sequence 3,8,16,13,24,50 only possible in the given options

 

As we know, there’s no rule about evaluation order of parameters of ‘+’

possible outcomes : 

  1. 3,8,16,13,24,50
  2. 8,3,16,13,24,50
  3. 13,24,3,8,16,50
  4. 13,24,8,3,16,50
Answer:

Related questions

14 votes
14 votes
3 answers
3
admin asked Feb 15, 2023
6,705 views
Which one of the following sequences when stored in an array at locations $A , \ldots, A[10]$ forms a max-heap?$23,17,10,6,13,14,1,5,7,12$$23,17,14,7,13,10,1,5,6,12$$23,1...