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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The elegant recursive solution (in pseudo-code):
then just use:
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
sumfunction:Then the code below is a test harness code for inserting nodes:
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):
The code to construct that tree and report the sum at various points is shown here:
This outputs (the correct):