ProgrammingVery hardCompetitive coding (CP)

A complete binary tree of 7 nodes is stored in an array with children of node i at 2i+1 and 2i+2. The values are v = {5, 3, 8, 1, 4, 9, 2}. How many root-to-leaf paths have a sum greater than 12? Compute with this program.

A complete binary tree of 7 nodes is stored in an array with children of node i at 2i+1 and 2i+2. The values are v = {5, 3, 8, 1, 4, 9, 2}. How many root-to-leaf paths have a sum greater than 12? Compute with this program.
#include <stdio.h>
int v[7] = {5, 3, 8, 1, 4, 9, 2};
int cnt(int i, int sum) {
    if (i >= 7) return 0;
    sum += v[i];
    if (2 * i + 1 >= 7) return sum > 12;
    return cnt(2 * i + 1, sum) + cnt(2 * i + 2, sum);
}
int main(void) {
    printf("%d", cnt(0, 0));
}
  1. A. 1
  2. B. 3
  3. C. 4
  4. D. 2

Correct answer: D. 2

The four root-to-leaf paths sum to 9, 12, 22 and 15. Only the last two exceed 12, so the answer is 2.

More C Programming questions

Exams that ask this topic