data-structures · intermediate · ~15 min

Sum of a binary tree

Aggregate a value recursively over a tree.

Challenge

With the same tnode_t, implement long tree_sum(tnode_t *root) returning the sum of all node values (0 for an empty tree).

Starter code

typedef struct tnode { int v; struct tnode *l, *r; } tnode_t;

long tree_sum(tnode_t *root) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.