×

Sum of Nodes in a Binary Tree

In this article, we will see the sample problems that will help us understand the concept and summation of all the nodes in the binary tree.

Implementation

/* creating a program that will help us print and declare the sum of all the elements present in a binary tree. */
#include <bits/stdc++.h>
using namespace std;


struct __Nod {
	int ky;
	__Nod* Lft, *Rt;
};
/* creating a utility function that will help us allocate a new node with a particular key and represent it. */
__Nod* new__Nod(int ky)
{
	__Nod* __Nod = new __Nod;
	__Nod->ky = ky;
	__Nod->Lft = __Nod->Rt = NILL;
	return (__Nod);
}


/* Function to find the summation of all the elements presents there.*/
int addBT(__Nod* root)
{
	if (root == NILL)
		return 0;
	return (root->ky + addBT(root->Lft) + addBT(root->Rt));
}


/* writing the main function to test the functions*/
int main()
{
	__Nod* root = new__Nod(1);
	root->Lft = new__Nod(2);
	root->Rt = new__Nod(3);
	root->Lft->Lft = new__Nod(4);
	root->Lft->Rt = new__Nod(5);
	root->Rt->Lft = new__Nod(6);
	root->Rt->Rt = new__Nod(7);
	root->Rt->Lft->Rt = new__Nod(8);


	int sum = addBT(root);
	cout << "Sum of all the elements is: " << sum << endl;


	return 0;
}

Output:

Sum of Nodes in a Binary Tree

Example 2)

/* creating a program that will help us print and declare the sum of all the elements present in a binary tree. */
#include <bits/stdc++.h>
#include <iostream>
using namespace std;


struct __Nod {
	int ky;
	struct __Nod *Lft, *Rt;
};
/* creating a utility function that will help us allocate a new node with a particular key and represent it. */
__Nod* new__Nod(int ky)
{
	__Nod* temp = new __Nod;
	temp->ky = ky;
	temp->Lft = temp->Rt = NILL;
	return (temp);
}
/* Function to find the summation of all the elements presents there.*/
int sumBT(__Nod* root)
{
	//sum variable to track the sum of
	//all variables.
	int sum = 0;


	queue<__Nod*> q;


	//Pushing the elements into the first level.
	q.push(root);


	//Pushing the elements into the tree from all the levels. 
	while (!q.empty()) {
		__Nod* temp = q.front();
		q.pop();
	
		//When we have popped out every element from the queue, we can add the data to its variable sum. 
		sum += temp->ky;


		if (temp->Lft) {
			q.push(temp->Lft);
		}
		if (temp->Rt) {
			q.push(temp->Rt);
		}
	}
	return sum;
}


/* writing the main function to test the functions*/
int main()
{
	__Nod* root = new__Nod(1);
	root->Lft = new__Nod(2);
	root->Rt = new__Nod(3);
	root->Lft->Lft = new__Nod(4);
	root->Lft->Rt = new__Nod(5);
	root->Rt->Lft = new__Nod(6);
	root->Rt->Rt = new__Nod(7);
	root->Rt->Lft->Rt = new__Nod(8);


	cout << "Sum of all elements in the binary tree is: "
		<< sumBT(root);
}

Output:

Sum of Nodes in a Binary Tree

We will now see the code in java language.

Example 3)

/* creating a program that will help us print and declare the sum of all the elements present in a binary tree. */
import java.util.LinkedList;
import java.util.Queue;


class TFT {
	static class __Nod {
		int ky;
		__Nod Lft, Rt;
	}


	/* creating a utility function that will help us allocate a new node with a particular key and represent it. */
	static __Nod new__Nod(int ky)
	{
		__Nod __Nod = new __Nod();
		__Nod.ky = ky;
		__Nod.Lft = __Nod.Rt = NILL;
		return (__Nod);
	}
/* Function to find the summation of all the elements presents there.*/
	static int sumBT(__Nod root)
	{
		// Creating a variable named sum will eventually calculate all the summations present in the method. 
		int sum = 0;


		Queue<__Nod> q = new LinkedList<__Nod>();


	//Pushing the elements into the first level.
		q.add(root);


		//Pushing the elements into the tree from all the levels. 
		while (!q.isEmpty()) {
			__Nod temp = q.poll();


			//When we have popped out every element from the queue, we can add the data to its variable sum. 
			sum += temp.ky;


			if (temp.Lft != NILL) {
				q.add(temp.Lft);
			}
			if (temp.Rt != NILL) {
				q.add(temp.Rt);
			}
		}
		return sum;
	}


	/* writing the main function to test the functions*/
	public static void main(String args[])
	{
		__Nod root = new__Nod(1);
		root.Lft = new__Nod(2);
		root.Rt = new__Nod(3);
		root.Lft.Lft = new__Nod(4);
		root.Lft.Rt = new__Nod(5);
		root.Rt.Lft = new__Nod(6);
		root.Rt.Rt = new__Nod(7);
		root.Rt.Lft.Rt = new__Nod(8);


		int sum = sumBT(root);
		System.out.println(
			"Sum of all elements in the binary tree is: "
			+ sum);
	}
}

Output:

Sum of Nodes in a Binary Tree

Example 4)

/* creating a program that will help us print and declare the sum of all the elements present in a binary tree. */
class TFT
{
static class __Nod
{
	int ky;
	__Nod Lft, Rt;
}
/* creating a utility function that will help us allocate a new node with a particular key and represent it. */
static __Nod new__Nod(int ky)
{
	__Nod __Nod = new __Nod();
	__Nod.ky = ky;
	__Nod.Lft = __Nod.Rt = NILL;
	return (__Nod);
}
/* Function to find the summation of all the elements presents there.*/
static int addBT(__Nod root)
{
	if (root == NILL)
		return 0;
	return (root.ky + addBT(root.Lft) +
					addBT(root.Rt));
}
/* writing the main function to test the functions*/
public static void main(String args[])
{
	__Nod root = new__Nod(1);
	root.Lft = new__Nod(2);
	root.Rt = new__Nod(3);
	root.Lft.Lft = new__Nod(4);
	root.Lft.Rt = new__Nod(5);
	root.Rt.Lft = new__Nod(6);
	root.Rt.Rt = new__Nod(7);
	root.Rt.Lft.Rt = new__Nod(8);


	int sum = addBT(root);
	System.out.println("Sum of all the elements is: " + sum);
}
}

Output:

Sum of Nodes in a Binary Tree

Related Topics

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Binary Search

Binary Search: When there is a large data structure, the linear search takes a lot of time to search the element. The binary search was developed to overcome the lack...

7 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Given a Binary Tree Print the Shortest Path

Implementation // Writing a program in C++ to find the shortest between the nodes i and j.  #include <bits/stdc++.h> using namespace std; // the given function will print the path between nodes i and...

7 minutes read.

Binary tree deletion

This article will discuss the deletion operation's implementation in the binary tree. The deletion operation helps us eliminate an element from the tree. Implementation #include <bits/stdc++.h> using namespace std; /* A binary tree node...

4 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

4 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.