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:
The total sum will be
7 + 36 + 1 + 2 + 4 + 5 = 64
now let’s see how to solve this problem.
Pseudo code:
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.
Solution in C++
#include <iostream> #include <stack> #include <map> using namespace std; // structure to hold binary tree node struct Node { int data; Node *left, *right; Node(int data) { this->data = data; this->left = this->right = nullptr; } }; int get_tree_sum(Node *root) { if (root == NULL) return 0; int sum = root->data + get_tree_sum(root -> left) + get_tree_sum(root -> right); return sum; } int main() { Node* root = nullptr; /* Binary tree: 16 / \ / \ 10 25 / \ / \ / \ / \ 7 15 18 30 */ root = new Node(16); root->left = new Node(10); root->right = new Node(25); root->left->left = new Node(7); root->left->right = new Node(15); root->right->left = new Node(18); root->right->right = new Node(30); cout<<"The Sum of the tree is "<<get_tree_sum(root)<<endl; return 0; }
Output:
The Sum of the tree is 121