Lesson 5 of 14

Sum of Values

Sum of All Node Values

To compute the sum of all values in a tree, use the same recursive pattern as traversal:

int tree_sum(struct Node *root) {
    if (root == NULL) return 0;
    return root->val + tree_sum(root->left) + tree_sum(root->right);
}

For the tree below, sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28:

        4
       / \
      2   6
     / \ / \
    1  3 5  7

How It Works

  1. Base case: empty tree (NULL) contributes 0.
  2. Recursive case: this node's value + sum of left subtree + sum of right subtree.

The order of addition does not matter (addition is associative), so any traversal order works.

Your Task

Implement int tree_sum(struct Node *root) that returns the sum of all node values.

TCC compiler loading...
Loading...
Click "Run" to execute your code.