Sum of all nodes in a binary tree
Last Updated :
02 Oct, 2023
Give an algorithm for finding the sum of all elements in a binary tree.

In the above binary tree sum = 106.
The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node's data.
Implementation:
C++
/* Program to print sum of all the elements of a binary tree */
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node* left, *right;
};
/* utility that allocates a new Node with the given key */
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return (node);
}
/* Function to find sum of all the elements*/
int addBT(Node* root)
{
if (root == NULL)
return 0;
return (root->key + addBT(root->left) + addBT(root->right));
}
/* Driver program to test above functions*/
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
int sum = addBT(root);
cout << "Sum of all the elements is: " << sum << endl;
return 0;
}
Java
// Java Program to print sum of
// all the elements of a binary tree
class GFG
{
static class Node
{
int key;
Node left, right;
}
/* utility that allocates a new
Node with the given key */
static Node newNode(int key)
{
Node node = new Node();
node.key = key;
node.left = node.right = null;
return (node);
}
/* Function to find sum
of all the elements*/
static int addBT(Node root)
{
if (root == null)
return 0;
return (root.key + addBT(root.left) +
addBT(root.right));
}
// Driver Code
public static void main(String args[])
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.left.right = newNode(8);
int sum = addBT(root);
System.out.println("Sum of all the elements is: " + sum);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 Program to print sum of all
# the elements of a binary tree
# Binary Tree Node
""" utility that allocates a new Node
with the given key """
class newNode:
# Construct to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Function to find sum of all the element
def addBT(root):
if (root == None):
return 0
return (root.key + addBT(root.left) +
addBT(root.right))
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(6)
root.right.right = newNode(7)
root.right.left.right = newNode(8)
sum = addBT(root)
print("Sum of all the nodes is:", sum)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
C#
using System;
// C# Program to print sum of
// all the elements of a binary tree
public class GFG
{
public class Node
{
public int key;
public Node left, right;
}
/* utility that allocates a new
Node with the given key */
public static Node newNode(int key)
{
Node node = new Node();
node.key = key;
node.left = node.right = null;
return (node);
}
/* Function to find sum
of all the elements*/
public static int addBT(Node root)
{
if (root == null)
{
return 0;
}
return (root.key + addBT(root.left) + addBT(root.right));
}
// Driver Code
public static void Main(string[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.left.right = newNode(8);
int sum = addBT(root);
Console.WriteLine("Sum of all the elements is: " + sum);
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// Javascript Program to print sum of
// all the elements of a binary tree
class Node
{
constructor(key)
{
this.key=key;
this.left=this.right=null;
}
}
/* Function to find sum
of all the elements*/
function addBT(root)
{
if (root == null)
return 0;
return (root.key + addBT(root.left) +
addBT(root.right));
}
// Driver Code
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.left.right = new Node(8);
let sum = addBT(root);
document.write("Sum of all the elements is: " + sum);
// This code is contributed by avanitrachhadiya2155
</script>
OutputSum of all the elements is: 36
Time Complexity: O(N)
Auxiliary Space: O(1), but if we consider space due to the recursion call stack then it would be O(h), where h is the height of the Tree.
Method 2 - Another way to solve this problem is by using Level Order Traversal. Every time when a Node is deleted from the queue, add it to the sum variable.
Implementation:
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
struct Node {
int key;
struct Node *left, *right;
};
// Utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
/*Function to find sum of all elements*/
int sumBT(Node* root)
{
//sum variable to track the sum of
//all variables.
int sum = 0;
queue<Node*> q;
//Pushing the first level.
q.push(root);
//Pushing elements at each level from
//the tree.
while (!q.empty()) {
Node* temp = q.front();
q.pop();
//After popping each element from queue
//add its data to the sum variable.
sum += temp->key;
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
return sum;
}
// Driver program
int main()
{
// Let us create Binary Tree shown in above example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
cout << "Sum of all elements in the binary tree is: "
<< sumBT(root);
}
//This code is contributed by Sarthak Delori
Java
// Java Program to print sum of
// all the elements of a binary tree
import java.util.LinkedList;
import java.util.Queue;
class GFG {
static class Node {
int key;
Node left, right;
}
// Utility function to create a new node
static Node newNode(int key)
{
Node node = new Node();
node.key = key;
node.left = node.right = null;
return (node);
}
/*Function to find sum of all elements*/
static int sumBT(Node root)
{
// sum variable to track the sum of
// all variables.
int sum = 0;
Queue<Node> q = new LinkedList<Node>();
// Pushing the first level.
q.add(root);
// Pushing elements at each level from
// the tree.
while (!q.isEmpty()) {
Node temp = q.poll();
// After popping each element from queue
// add its data to the sum variable.
sum += temp.key;
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
}
return sum;
}
// Driver Code
public static void main(String args[])
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.left.right = newNode(8);
int sum = sumBT(root);
System.out.println(
"Sum of all elements in the binary tree is: "
+ sum);
}
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)
Python3
# Python3 Program to print sum of all
# the elements of a binary tree
# Binary Tree Node
class newNode:
# Utility function to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Function to find sum of all the element
def sumBT(root):
# sum variable to track the sum of
# all variables.
sum = 0
q = []
# Pushing the first level.
q.append(root)
# Pushing elements at each level from
# the tree.
while len(q) > 0:
temp = q.pop(0)
# After popping each element from queue
# add its data to the sum variable.
sum += temp.key
if (temp.left != None):
q.append(temp.left)
if temp.right != None:
q.append(temp.right)
return sum
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(6)
root.right.right = newNode(7)
root.right.left.right = newNode(8)
print("Sum of all elements in the binary tree is: ", sumBT(root))
# This code is contributed by
# Abhijeet Kumar(abhijeet19403)
C#
// C# Program to print sum of
// all the elements of a binary tree
using System;
using System.Collections.Generic;
public class GFG {
public class Node {
public int key;
public Node left, right;
}
// Utility function to create a new node
public static Node newNode(int key)
{
Node node = new Node();
node.key = key;
node.left = node.right = null;
return (node);
}
/*Function to find sum of all elements*/
public static int sumBT(Node root)
{
// sum variable to track the sum of
// all variables.
int sum = 0;
Queue<Node> q = new Queue<Node>();
// Pushing the first level.
q.Enqueue(root);
// Pushing elements at each level from
// the tree.
while (q.Count!=0) {
Node temp = q.Dequeue();
// After popping each element from queue
// add its data to the sum variable.
sum += temp.key;
if (temp.left != null) {
q.Enqueue(temp.left);
}
if (temp.right != null) {
q.Enqueue(temp.right);
}
}
return sum;
}
// Driver Code
public static void Main(string[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.left.right = newNode(8);
Console.WriteLine("Sum of all elements in the binary tree is: "
+ sumBT(root));
}
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)
JavaScript
<script>
// Javascript Program to print sum of
// all the elements of a binary tree
class Node
{
// Utility function to create a new node
constructor(key)
{
this.key=key;
this.left=this.right=null;
}
}
/* Function to find sum
of all the elements*/
function sumBT(root)
{
// sum variable to track the sum of
// all variables.
let sum = 0;
let q = [];
// Pushing the first level.
q.push(root);
// Pushing elements at each level from
// the tree.
while (q.length != 0) {
let temp = q.shift();
// After popping each element from queue
// add its data to the sum variable.
sum += temp.key;
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
}
return sum;
}
// Driver Code
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.left.right = new Node(8);
document.write("Sum of all elements in the binary tree is: " + sumBT(root));
// This code is contributed by Abhijeet Kumar(abhijeet19403)
</script>
OutputSum of all elements in the binary tree is: 36
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: Using Morris traversal:
The Morris Traversal algorithm is an in-order tree traversal algorithm that does not require the use of a stack or recursion, and uses only constant extra memory. The basic idea behind the Morris Traversal algorithm is to use the right child pointers of the nodes to create a temporary link back to the node's parent, so that we can easily traverse the tree without using any extra memory.
Follow the steps below to implement the above idea:
- Initialize a variable sum to 0 to keep track of the sum of all nodes in the binary tree.
- Initialize a pointer root to the root of the binary tree.
- While root is not null, perform the following steps:
If the left child of root is null, add the value of root to sum, and move to the right child of root.
If the left child of root is not null, find the rightmost node of the left subtree of root and create a temporary link back to root.
Move to the left child of root. - After the traversal is complete, return sum.
Below is the implementation of the above approach:
C++
// C++ code to implement the morris traversal approach
#include <iostream>
using namespace std;
// Definition of a binary tree node
struct Node {
int val;
Node* left;
Node* right;
Node(int v)
: val(v)
, left(nullptr)
, right(nullptr)
{
}
};
// Morris Traversal function to find the sum of all nodes in
// a binary tree
long int sumBT(Node* root)
{
long int sum = 0;
while (root != nullptr) {
if (root->left
== nullptr) { // If there is no left child, add
// the value of the current node
// to the sum and move to the
// right child
sum += root->val;
root = root->right;
}
else { // If there is a left child
Node* prev = root->left;
while (
prev->right != nullptr
&& prev->right
!= root) // Find the rightmost node
// in the left subtree of
// the current node
prev = prev->right;
if (prev->right
== nullptr) { // If the right child of the
// rightmost node is null, set
// it to the current node and
// move to the left child
prev->right = root;
root = root->left;
}
else { // If the right child of the rightmost
// node is the current node, set it to
// null, add the value of the current
// node to the sum and move to the right
// child
prev->right = nullptr;
sum += root->val;
root = root->right;
}
}
}
return sum;
}
// Driver code
int main()
{
// Example binary tree: 1
// / \
// 2 3
// / \
// 4 5
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
// Find the sum of all nodes in the binary tree
long int sum = sumBT(root);
cout << "Sum of all nodes in the binary tree is " << sum
<< endl;
return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot
Java
// Java code to implement the Morris traversal approach
class Node {
int val;
Node left, right;
Node(int item) {
val = item;
left = right = null;
}
}
class GFG {
// Function to find the sum of all nodes in a binary tree
static long sumBT(Node root) {
long sum = 0;
while (root != null) {
if (root.left == null) { // If there is no left child, add
// the value of the current node
// to the sum and move to the
// right child
sum += root.val;
root = root.right;
} else { // If there is a left child
Node prev = root.left;
while (prev.right != null && prev.right != root) // Find the rightmost node
// in the left subtree of
// the current node
prev = prev.right;
if (prev.right == null) { // If the right child of the
// rightmost node is null, set
// it to the current node and
// move to the left child
prev.right = root;
root = root.left;
} else { // If the right child of the rightmost
// node is the current node, set it to
// null, add the value of the current
// node to the sum and move to the right
// child
prev.right = null;
sum += root.val;
root = root.right;
}
}
}
return sum;
}
// Driver code
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
// Find the sum of all nodes in the binary tree
long sum = sumBT(root);
System.out.println("Sum of all nodes in the binary tree is : " + sum);
}
}
//This code is contributed by Veerendra_Singh_Rajpoot
Python3
# Definition of a binary tree node
class Node:
def __init__(self, v):
self.val = v
self.left = None
self.right = None
# Morris Traversal function to find the sum of all nodes in
# a binary tree
def sumBT(root):
sum = 0
while root:
if root.left is None:
# If there is no left child, add the value of the
# current node to the sum and move to the right child
sum += root.val
root = root.right
else:
# If there is a left child
prev = root.left
while prev.right and prev.right != root:
# Find the rightmost node in the left subtree
# of the current node
prev = prev.right
if prev.right is None:
# If the right child of the rightmost node is null,
# set it to the current node and move to the left child
prev.right = root
root = root.left
else:
# If the right child of the rightmost node is the
# current node, set it to null, add the value of
# the current node to the sum and move to the right child
prev.right = None
sum += root.val
root = root.right
return sum
# Driver code
if __name__ == "__main__":
# Example binary tree: 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Find the sum of all nodes in the binary tree
sum = sumBT(root)
print("Sum of all nodes in the binary tree is", sum)
C#
using System;
// Definition of a binary tree node
public class Node
{
public int val;
public Node left;
public Node right;
public Node(int v)
{
val = v;
left = null;
right = null;
}
}
public class MorrisTraversal
{
// Morris Traversal function to find the sum of all nodes in
// a binary tree
public static long SumBT(Node root)
{
long sum = 0;
while (root != null)
{
if (root.left == null)
{
// If there is no left child, add
// the value of the current node
// to the sum and move to the
// right child
sum += root.val;
root = root.right;
}
else
{// If there is a left child
Node prev = root.left;
// Find the rightmost node
// in the left subtree of
// the current node
while (prev.right != null && prev.right != root)
{
prev = prev.right;
}
// If the right child of the
// rightmost node is null, set
// it to the current node and
// move to the left child
if (prev.right == null)
{
prev.right = root;
root = root.left;
}
// If the right child of the rightmost
// node is the current node, set it to
// null, add the value of the current
// node to the sum and move to the right
// child
else
{
prev.right = null;
sum += root.val;
root = root.right;
}
}
}
return sum;
}
// Driver code
public static void Main(string[] args)
{
// Example binary tree: 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
// Find the sum of all nodes in the binary tree
long sum = SumBT(root);
Console.WriteLine("Sum of all nodes in the binary tree is " + sum);
// Clean up memory (optional)
root = null;
// Prevent the console window from closing immediately
Console.ReadLine();
}
}
// This code is contributed by rambabuguphka
JavaScript
// Definition of a binary tree node
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Morris Traversal function to find the sum of all nodes in a binary tree
function sumBT(root) {
let sum = 0;
while (root !== null) {
if (root.left === null) {
// If there is no left child, add the value of the current node to the sum
// and move to the right child
sum += root.val;
root = root.right;
} else {
// If there is a left child
let prev = root.left;
while (prev.right !== null && prev.right !== root) {
// Find the rightmost node in the left subtree of the current node
prev = prev.right;
}
if (prev.right === null) {
// If the right child of the rightmost node is null, set it to the current node
// and move to the left child
prev.right = root;
root = root.left;
} else {
// If the right child of the rightmost node is the current node,
// set it to null, add the value of the current node to the sum,
// and move to the right child
prev.right = null;
sum += root.val;
root = root.right;
}
}
}
return sum;
}
// Driver code
function main() {
// Example binary tree: 1
// / \
// 2 3
// / \
// 4 5
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// Find the sum of all nodes in the binary tree
const sum = sumBT(root);
console.log("Sum of all nodes in the binary tree is " + sum);
}
// Call the main function to start the program
main();
OutputSum of all nodes in the binary tree is 15
Time Complexity: O(n) , Because of all the nodes are traversing only once.
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read