Sum of all nodes in Binary Tree in C

Sum of all nodes in Binary Tree

Here, in this page we will write a C program to find the sum of all nodes in the given binary tree.

First, we will traverse through the left sub-tree and calculate the sum of nodes present in the left sub-tree. Similarly, we calculate the sum of nodes present in the right sub-tree and calculate total sum by adding the root’s data.

sum of all nodes

Algorithm :

 

  • Create a function say, calculateSum() that will calculate the sum of nodes present in the binary tree.
  • It checks whether the root is null, which means that the tree is empty.
  • If the tree is not empty, traverse through left subtree, calculate the sum of nodes and store it in variable say, sumLeft.
  • Then, traverse through the right subtree, calculate the sum of nodes and store it in variable say, sumRight.
  • Finally, calculate total sum = root->data + sumLeft + sumRight.
sum of all nodes in C

Code in C Based on Above Algorithm

#include <stdio.h>  
#include <stdlib.h>

struct node{
int data;
struct node *left;
struct node *right;
};

struct node *root = NULL;
struct node* createNode(int data){
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

int calculateSum(struct node *temp){
int sum, sumLeft, sumRight;
sum = sumRight = sumLeft = 0;

if(root == NULL) {
printf("Tree is empty\n");
return 0;
}
else
{
if(temp->left != NULL)
sumLeft = calculateSum(temp->left);
if(temp->right != NULL)
sumRight = calculateSum(temp->right);

sum = temp->data + sumLeft + sumRight;
return sum;
}
}

int main()
{
root = createNode(10);
root->left = createNode(20);
root->right = createNode(30);
root->left->left = createNode(40);
root->right->left = createNode(50);
root->right->right = createNode(60);

printf("Sum of all nodes of binary tree: %d", calculateSum(root));
return 0;
}
Output :


Sum of all nodes of binary tree: 210