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

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

by nikoo28
0 comment

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));
	}
}

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More