Sum of all nodes in a binary tree


06 Jul, 2022

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.  
C++
Java
Python3
C#
Javascript
 

 
 










/* 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 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 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)






 

 
 










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






 

 
 










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






Sum of all the elements is: 36
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.
C++
Java
Python3
C#
Javascript
 

 
 










#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 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 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# 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)






 

 
 










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






Sum of all elements in the binary tree is: 36
Time Complexity: O(n)Auxiliary Space: O(n)
Sum of all nodes in a binary tree | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersSum of all nodes in a binary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:47•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bD9oYzwfZ1w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Prakriti Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
andrew1234
shrikanth13
SHUBHAMSINGH10
Sheenam Yadav
avanitrachhadiya2155
sarthakdelori10
abhijeet19403

FactSet


Tree

FactSet
Tree
Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.