data-structures · intermediate · ~15 min
Aggregate a value recursively over a tree.
Add up every value stored in a binary tree.
Given the node type typedef struct tnode { int v; struct tnode *l, *r; } tnode_t;, implement long tree_sum(tnode_t *root) that returns the sum of the v field of every node in the tree.
root: a pointer to the root node (the type tnode_t is given, with an int v and left/right child pointers l and r). May be NULL.
long: the sum of all node values; 0 for an empty tree.
NULL -> 0
tree with values 1, 2, 3 -> 6
NULL) returns 0.long so a large tree does not overflow.root: pointer to a tnode_t (given: int v; tnode_t *l, *r;); may be NULL.
long: sum of every node's v value (0 if empty).
Accumulate in long to avoid overflow.
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.