Add all the node values in a Binary Tree or Sum of a Binary tree

In this chapter, we shall see how to add all the nodes value.

Problem Statement:

Given a binary tree root node, return the sum of all the nodes of the tree.

Example:

Consider the tree below:

sum_of_all_nodes_in_a_binary_tree

The total sum will be
7 + 36 + 1 + 2 + 4 + 5 = 64

Now let’s see how to solve this problem.

int get_tree_sum(node *root)
{
	if root == NULL
		return 0

	int sum = root->value +
				get_tree_sum(root -> left) +
				get_tree_sum(root -> right) 
	return sum
}

According to the code above, we have a base condition i.e if the node is null return 0.

Then the statement “int sum = root->value + get_tree_sum(root -> left) + get_tree_sum(root -> right)”, first we take the sum of left sub tree of the root, then we take the right sub tree of the root.

Then once we get the left sub tree and right sub tree, we add it to the root, then returning the total sum of the tree.

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *