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
Sum of all leaf nodes of binary tree
Given a binary tree, find the sum of all the leaf nodes.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24 Recommended PracticeSum of Leaf NodesTry It! The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the lea
5 min read
Sum of all the Boundary Nodes of a Binary Tree
Given a binary tree, the task is to print the sum of all the boundary nodes of the tree. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 28 Input: 1 / \ 2 3 \ / 4 5 \ 6 / \ 7 8 Output: 36 Approach: We have already discussed the Boundary Traversal of a Binary tree. Here we will find the sum of the
10 min read
Print all K-sum levels in a Binary Tree
Given a Binary Tree and an integer K where the tree has positive and negative nodes, the task is to print the elements of the level whose sum equals K. If no such result exists, then print "Not Possible". Examples: Input: -10 / \ 2 -3 / \ \ 4 15 -6 / \ / 7 -8 9 K = 13 Output: 4 15 -6 Explanation: Le
8 min read
Print all full nodes in a Binary Tree
Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty. Examples: Input : 10 / \ 8 2 / \ / 3 5 7 Output : 10 8 Input : 1 / \ 2 3 / \ 4 6 Output : 1 3 This is a simple problem. We do any of the traÂverÂsals (Inorder, PreÂorde
4 min read
Print all k-sum paths in a binary tree
A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as k. A path can start from any node and end at any node and must be downward only, i.e. they need not be root node and leaf node; and negative numbers can also be there in the tree. Examples: Inpu
9 min read
Sum of nodes at maximum depth of a Binary Tree
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 While traversing the nodes compare th
15+ min read
Find sum of all left leaves in a given Binary Tree
Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6. Recommended PracticeSum of Left Leaf NodesTry It! The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then a
15+ min read
Sum of nodes in top view of binary tree
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, the task is to print the sum of nodes in top view.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 16 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 12 Approach: The idea is to put nodes of same hori
13 min read
Sum of cousins of a given node in a Binary Tree
Given a binary tree and data value of a node. The task is to find the sum of cousin nodes of given node. If given node has no cousins then return -1. Note: It is given that all nodes have distinct values and the given node exists in the tree. Examples: Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 1
11 min read
Sum of heights of all individual nodes in a binary tree
Given a binary tree, find the sum of heights of all individual nodes in the tree. Example: For this tree: 1). Height of Node 1 - 3 2). Height of Node 2 - 2 3). Height of Node 3 - 1 4). Height of Node 4 - 1 5). Height of Node 5 - 1 Adding all of them = 8 Prerequisites:- Height of binary tree Simple S
11 min read