The Wayback Machine - https://web.archive.org/web/20240721175915/https://www.geeksforgeeks.org/sum-nodes-binary-tree/
Open In App

Sum of all nodes in a binary tree

Last Updated : 02 Oct, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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>


Output

Sum 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>


Output

Sum 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:

  1. Initialize a variable sum to 0 to keep track of the sum of all nodes in the binary tree.
  2. Initialize a pointer root to the root of the binary tree.
  3. 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.
  4. After the traversal is complete, return sum.

Below is the implementation of the above approach:

C++





Java





Python3





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


Output

Sum 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 nodes in a binary tree having only the left child nodes
Given a binary tree, the task is to find the sum of binary tree nodes having only the left child nodes. Example: Input: 8 / \ 3 7 / \ / 5 6 0 / / 1 2Output: 18 Explanation: Nodes with values 5, 6, and 7 are the ones that have only the left child nodes Input: 2 / \ 3 1 / / 5 6Output: 4 Approach: The given problem can be solved by traversing the bina
6 min read
Sum of Bitwise AND of the sum of all leaf and non-leaf nodes for each level of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to find the sum of Bitwise AND of the sum of all leaf nodes and the sum of all non-leaf nodes for each level in the given Tree. Examples: Input: Below is the given tree: 5 / \ 3 9 / \ 6 4 \ 7Output: 5Explanation: For Level 1: leaf node sum = 0, non-leaf node sum = 5. So, 0&amp;5 = 0. For Level
10 min read
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weighted string when concatenated with the strings of the sub-tree nodes becomes a pangram. Pangram: A pangram is a sentence containing every letter of the English Alphabet. Examples: Input: Output: 1 Only the weighted string of sub-tree of
7 min read
Count of nodes in a binary tree having their nodes in range [L, R]
Given a Binary Tree consisting of N nodes and two positive integers L and R, the task is to find the count of nodes having their value in the range [L, R]. Examples: Input: Tree in the image below, L = 4, R = 15 Output: 2Explanation: The nodes in the given Tree that lies in the range [4, 15] are {5, 10}. Input: Tree in the image below, L = 8, R = 2
11 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ 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 Solution: We get the height of all individual nodes
11 min read
Find sum of all nodes of the given perfect binary tree
Given a positive integer L which represents the number of levels in a perfect binary tree. Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n, where n is the number of leaf nodes. And the parent node is the sum of the two child nodes. Our task is to write a program to print the sum of all of the nodes of this pe
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg