×

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

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 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.

Introduction and Implementation of Bloom Filter

It often happens with many of us that when we create an account on some applications like Github, it shows us that the username already exists. You can add some...

4 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.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

6 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

Remove duplicates from an unsorted Linked List

Remove duplicates from an unsorted Linked List This article will explain how we can remove duplicates from unsorted linked lists. Here we have given an unsorted singly linked list and will...

3 minutes read.

Assembly Line Scheduling

If we take an example of a car factory, there are two assembly lines. In an assembly line, we can assemble and repair the parts of a car. Now, suppose...

5 minutes read.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.

Insertion Sort vs Bubble Sort

In this article, we will see the major differences between Insertion Sort and Bubble Sort. Before that, let’s have a quick overview of what these sorting algorithms are and what’s...

4 minutes read.