csguy11 csguy11 - 1 year ago 66
C++ Question

C++: Sum of all node values of a binary tree

I'm preparing for a job interview. I was stuck at one of the binary tree questions:

How can we calculate the sum of the values present in all the nodes of a binary tree?

Thanks in advance.

Answer Source

The elegant recursive solution (in pseudo-code):

def sum (node):
    if node == NULL:
        return 0
    return node->value + sum (node->left) + sum (node->right)

then just use:

total = sum (root)

This correctly handles the case of a NULL root node.

And if you want to see it in action in C++, here's some code using that algorithm. First, the structure for a node and the sum function:

#include <iostream>

typedef struct sNode {
    int value;
    struct sNode *left;
    struct sNode *right;
} tNode;

int sum (tNode *node) {
    if (node == 0) return 0;
    return node->value + sum (node->left) + sum (node->right);

Then the code below is a test harness code for inserting nodes:

static tNode *addNode (tNode *parent, char leftRight, int value) {
    tNode *node = new tNode();
    node->value = value;
    node->left = 0;
    node->right = 0;

    if (parent != 0) {
        if (leftRight == 'L') {
            parent->left = node;
        } else {
            parent->right = node;

    return node;

And, finally, the main function for constructing the following tree, one that covers all of the valid possibilities (empty node, node with two children, node with no children, node with one right child and node with one left child):

   /  \
  7    20
 /       \
3         99

The code to construct that tree and report the sum at various points is shown here:

int main (void) {
    // Empty tree first.

    tNode *root = 0;

    std::cout << sum (root) << '\n';

    // Then a tree with single node (10).

    root = addNode (0, ' ', 10);

    std::cout << sum (root) << '\n';

    // Then one with two subnodes (10, 7, 20).

    addNode (root,'L',7);
    addNode (root,'R',20);

    std::cout << sum (root) << '\n';

    // Then, finally, the full tree as per above.

    addNode (root->left,'L',3);
    addNode (root->left->left,'R',4);
    addNode (root->left->left->right,'R',6);
    addNode (root->right,'R',99);

    std::cout << sum (root) << '\n';

    return 0;

This outputs (the correct):

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download