Site icon Study Algorithms

Given a binary tree, find the sum of all its elements.

Question: Given the root pointer to a binary tree, find the sum of all its elements.

Input: Sample Tree (Pointer to node 1 is given).
tree_insert_element_1
Output: Sum = 15

This is a very simple problem. Since the tree follows a recursive sub-structure, we can recursively call left tree sum, right tree sum and then add their values to the current node data.

#include<stdio.h>
#include<malloc.h>

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

int sumOfBinaryTree(struct binaryTreeNode * root)
{
	// Terminating condition
	if(root == NULL)
	{
		return 0;
	}
	else
	{
		//Recursively call the addition of root + left + right
		return (root -> data + sumOfBinaryTree(root -> left) + sumOfBinaryTree(root -> right));
	}
}
Exit mobile version