sum of leaves in Binary Tree

we have a binary tree in scheme like this  :      (node (leaf 1) (node (leaf 2) (leaf 3)))
we want to calculate sum of  number in leaves

(display (sum '(node (leaf 1) (node (leaf 2) (leaf 3)))))
result => 6
Aida BehroozianAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bill PrewIT / Software Engineering ConsultantCommented:
Are you working in any specific programming language, or just a conceptual question?

Conceptually there are typically two approaches to these type of questions, iterative, or recursive.

In an iterative approach, you "walk the tree" typically starting from the root, and visit each node in sequence by chasing the linkages between branches and leafs, and add each leaf value to the running total.

In a recursive approach you also start from the root node, and then call a recursive function that process a single node.  Each node passed to the function can have either branches or leafs in it, or both in some constructs.  As it visits each branch under that node it calls itself again for each child branch.  For each leaf it adds the leaf value to the running total, in this case passed in to the function also, and returns that value as the return from the function.  A little reading on recursive program will make it even clearer.

Bill PrewIT / Software Engineering ConsultantCommented:
Not sure if this will help or hurt, but check out youtube for some videos as well, like:

note, you wouldn't call a node with child nodes a 'leaf'. leaves are nodes without children.

as Bill has told, you have to iterate the tree in order to sum up all number values. in a binary tree each node has either two, one or no children.

the easiest approach to iterate all nodes is the recursive one as explained by Bill.

it is easy as you don't have to go back to a parent node in order to take the second choice down. instead you were using the fact that each child node left or right actually is the root node of a sub-tree. so for an iteration you would begin with the root node and call a function that calls the same function again if there is a left child node and the same function if there is a right child node. the call would end if a leaf node was called.

typedef struct Node
        struct Node * left_child;
        struct Node * right_child;
        int number;
} Node;

int calc_sum_of_binary_tree(Node * root, int total)
       total += root->number;
       if (root->left_child) 
            total = calc_sum_of_binary_tree(root->left_child, total);
       if (root->right_child) 
            total = calc_sum_of_binary_tree(root->right_child, total);
       return total; 

int main()
    Node nodes[10] = 
        { &nodes[1], &nodes[2], 7 }, //                           0
        { &nodes[3], &nodes[4], 1 }, //                 1                     2
        { &nodes[5], &nodes[6], 3 }, //            3         4            5        6
        { &nodes[7], NULL,      5 }, //        7
        { &nodes[8], &nodes[9], 2 }, //     8     9
        { NULL,      NULL,      9 }, //         
        { NULL,      NULL,      4 }, //         
        { NULL,      NULL,      8 }, //         
        { NULL,      NULL,      1 }, //         
        { NULL,      NULL,      2 }, //         

    int total = calc_sum_of_binary_tree(&nodes[0], 0);

    return total;

Open in new window

note, the code above is c code but easily can be improved into c++ or c# code


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.