Sum of All Nodes in a Binary Tree

Last Updated : 7 May, 2026

Given a binary tree, find the sum of all Nodes in a binary tree.

Examples:

Input: root = [15, 10, 20, 8, 12, 16, 25]

2056957867

Output: 106
Explanation: The sum of all the nodes is 15 + 10 + 20 + 8 + 12 + 16 + 25 = 106.

Input: root = [1, 3, 2]

2056957868

Output: 6
Explanation: The sum of all the nodes is 1 + 2 + 3 = 6.

Try It Yourself
redirect icon

The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node's data. 

Consider the following tree for example to understand the flow.

heightTree3

sumBT('12') = 12 + sumBT('8') + sumBT('18') = 12 + 24 + 18 = 54
because recursively 
sumBT('8') =  8 + sumBT('5') + sumBT('11') = 8 + 5 + 111 = 24
sumBT('18') = 18 + sumBT(NULL) + sumBT('NULL) = 18 + 0 + 0 = 18
sumBT("5") = 5 + sumBT(NULL), + sumBT('NULL)) = 5 + 0 + 0 = 5
sumBT("11") = 11 + sumBT(NULL) + sumBT('NULL)) = 11 + 0 + 0 = 11

C++
// Program to print sum of all the elements of a binary tree /
#include <bits/stdc++.h>
using namespace std;


class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = right = nullptr;
    }
};

int sumBT(Node *root)
{

    if (root == NULL)
        return 0;

    return (root->data + sumBT(root->left) + sumBT(root->right));
}

// Driver code
int main()
{
    Node *root = new Node(15);
    root->left = new Node(10);
    root->right = new Node(20);
    root->left->left = new Node(8);
    root->left->right = new Node(12);
    root->right->left = new Node(16);
    root->right->right = new Node(25);

    int sum = sumBT(root);

    cout << "Sum of all the elements is: " << sum << endl;

    return 0;
}
C
// Program to print sum of all the elements of a binary tree 
#include <stdio.h>
#include <stdlib.h>


struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(int val) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = val;
    node->left = node->right = NULL;
    return node;
}

// Function to find sum of all elements 
int sumBT(struct Node* root) {

    if (root == NULL)
        return 0;

    return (root->data + sumBT(root->left) + sumBT(root->right));
}

// Driver code 
int main()
{
    struct Node* root = newNode(15);
    root->left = newNode(10);
    root->right = newNode(20);
    root->left->left = newNode(8);
    root->left->right = newNode(12);
    root->right->left = newNode(16);
    root->right->right = newNode(25);

    int sum = sumBT(root);

    printf("Sum of all the elements is: %d\n", sum);

    return 0;
}
Java
/* Program to print sum of all the elements of a binary tree
 */
import java.util.*;

class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

public class GfG {
    public static int sumBT(Node root)
    {
        if (root == null)
            return 0;

        return (root.data + sumBT(root.left)
                + sumBT(root.right));
    }

    public static void main(String[] args)
    {
        Node root = new Node(15);
        root.left = new Node(10);
        root.right = new Node(20);
        root.left.left = new Node(8);
        root.left.right = new Node(12);
        root.right.left = new Node(16);
        root.right.right = new Node(25);

        int sum = sumBT(root);

        System.out.println("Sum of all the elements is: "
                           + sum);
    }
}
Python
# Program to print sum of all the elements of a binary tree

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

class Solution:
    def sumBT(self, root):
        
        if root is None:
            return 0

        return (root.data + self.sumBT(root.left) + self.sumBT(root.right))


# Driver code
def main():
    root = Node(15)
    root.left = Node(10)
    root.right = Node(20)
    root.left.left = Node(8)
    root.left.right = Node(12)
    root.right.left = Node(16)
    root.right.right = Node(25)

    obj = Solution()
    sum_val = obj.sumBT(root)

    print("Sum of all the elements is:", sum_val)


if __name__ == "__main__":
    main()
C#
using System;
using System.Collections.Generic;

// Definition for Node
public class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GfG {
    
    public static int sumBT(Node root)
    {

        if (root == null)
            return 0;

        return (root.data + sumBT(root.left)
                + sumBT(root.right));
    }

    static void Main()
    {

        Node root = new Node(15);
        root.left = new Node(10);
        root.right = new Node(20);
        root.left.left = new Node(8);
        root.left.right = new Node(12);
        root.right.left = new Node(16);
        root.right.right = new Node(25);

        int sum = GfG.sumBT(root);

        Console.WriteLine("Sum of all the elements is: "
                          + sum);
    }
}
JavaScript
/* Program to print sum of all the elements of a binary tree */

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

class Solution {
    sumBT(root) {
        
        if (root === null)
            return 0;

        return (root.data + this.sumBT(root.left) + this.sumBT(root.right));
    }
}

// driver code
function main() {

    let root = new Node(15);
    root.left = new Node(10);
    root.right = new Node(20);
    root.left.left = new Node(8);
    root.left.right = new Node(12);
    root.right.left = new Node(16);
    root.right.right = new Node(25);

    let obj = new Solution();
    let sum = obj.sumBT(root);

    console.log("Sum of all the elements is:", sum);
}

main();

Output
Sum of all the elements is: 106

Time Complexity: O(n)
Auxiliary Space: O(h), 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.

Using Level Order Traversal (BFS) - O(n) Time O(n) Space

The Idea is to traverse the tree level by level using a queue (BFS). Start from the root, add each node’s value to the sum, and push its left and right children into the queue. Repeat until all nodes are processed.

C++
// Program to print sum of all the elements of a binary tree using Level Order Traversal
#include <bits/stdc++.h>
using namespace std;

// Definition for Node
class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = right = nullptr;
    }
};

int sumBT(Node *root)
{

    //sum variable to track the sum of
    //all variables.
    int sum = 0;

    queue<Node *> q;

    // push root node
    q.push(root);

    // iterate level order traversal
    while (!q.empty())
    {
        Node *temp = q.front();
        q.pop();

        //After popping each element from queue
         //add its data to the sum variable.
        sum += temp->data;

        // push left child
        if (temp->left)
        {
            q.push(temp->left);
        }

        // push right child
        if (temp->right)
        {
            q.push(temp->right);
        }
    }

    return sum;
}

// Driver code /
int main()
{
    Node *root = new Node(15);
    root->left = new Node(10);
    root->right = new Node(20);
    root->left->left = new Node(8);
    root->left->right = new Node(12);
    root->right->left = new Node(16);
    root->right->right = new Node(25);

    cout << "Sum of all elements in the binary tree is: " << sumBT(root);

    return 0;
}
C
// Program to print sum of all the elements of a binary tree using Level Order Traversal 
#include <stdio.h>
#include <stdlib.h>

// Definition for Node 
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(int val) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = val;
    node->left = node->right = NULL;
    return node;
}

// Queue implementation 
struct Queue {
    struct Node* arr[1000];
    int front, rear;
};

void init(struct Queue* q) {
    q->front = q->rear = 0;
}

void push(struct Queue* q, struct Node* node) {
    q->arr[q->rear++] = node;
}

struct Node* pop(struct Queue* q) {
    return q->arr[q->front++];
}

int isEmpty(struct Queue* q) {
    return q->front == q->rear;
}

// Function to find sum of all elements 
int sumBT(struct Node* root) {

    int sum = 0;

    struct Queue q;
    init(&q);

    push(&q, root);

    while (!isEmpty(&q)) {
        struct Node* temp = pop(&q);

        sum += temp->data;

        if (temp->left) {
            push(&q, temp->left);
        }

        if (temp->right) {
            push(&q, temp->right);
        }
    }

    return sum;
}

// Driver code 
int main()
{
    struct Node* root = newNode(15);
    root->left = newNode(10);
    root->right = newNode(20);
    root->left->left = newNode(8);
    root->left->right = newNode(12);
    root->right->left = newNode(16);
    root->right->right = newNode(25);

    printf("Sum of all elements in the binary tree is: %d", sumBT(root));

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

// Definition for Node
class Node {
  public int data;
  public Node left;
  public Node right;

  public Node(int val) {
    data = val;
    left = right = null;
  }
}

public class GfG {
    
  public static int sumBT(Node root) {
    // sum variable to store total sum
    int sum = 0;

    Queue<Node> q = new LinkedList<>();

    // push root node
    q.add(root);

    // iterate level order traversal
    while (!q.isEmpty()) {
      Node temp = q.poll();

      // add node data to sum
      sum += temp.data;

      // push left child
      if (temp.left!= null) {
        q.add(temp.left);
      }

      // push right child
      if (temp.right!= null) {
        q.add(temp.right);
      }
    }

    return sum;
  }

  public static void main(String[] args) {
    Node root = new Node(15);
    root.left = new Node(10);
    root.right = new Node(20);
    root.left.left = new Node(8);
    root.left.right = new Node(12);
    root.right.left = new Node(16);
    root.right.right = new Node(25);

    System.out.println("Sum of all elements in the binary tree is: " + sumBT(root));
  }
}
Python
# Program to print sum of all the elements of a binary tree using Level Order Traversal

from collections import deque

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

class Solution:
    def sumBT(self, root):

        sum = 0

        q = deque()
        q.append(root)

        while q:
            temp = q.popleft()

            sum += temp.data

            if temp.left:
                q.append(temp.left)

            if temp.right:
                q.append(temp.right)

        return sum


# Driver code
def main():
    root = Node(15)
    root.left = Node(10)
    root.right = Node(20)
    root.left.left = Node(8)
    root.left.right = Node(12)
    root.right.left = Node(16)
    root.right.right = Node(25)

    obj = Solution()
    print("Sum of all elements in the binary tree is:", obj.sumBT(root))


if __name__ == "__main__":
    main()
C#
using System;
using System.Collections.Generic;

public class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GfG {

    public static int sumBT(Node root)
    {

        int sum = 0;

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node temp = q.Dequeue();

            sum += temp.data;

            if (temp.left != null) {
                q.Enqueue(temp.left);
            }

            if (temp.right != null) {
                q.Enqueue(temp.right);
            }
        }

        return sum;
    }

    static void Main()
    {

        Node root = new Node(15);
        root.left = new Node(10);
        root.right = new Node(20);
        root.left.left = new Node(8);
        root.left.right = new Node(12);
        root.right.left = new Node(16);
        root.right.right = new Node(25);

        Console.WriteLine(
            "Sum of all elements in the binary tree is: "
            + sumBT(root));
    }
}
JavaScript
// Program to print sum of all the elements of a binary tree using Level Order Traversal 

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

class Solution {
    sumBT(root) {

        let sum = 0;

        let q = [];
        q.push(root);

        while (q.length > 0) {
            let temp = q.shift();

            sum += temp.data;

            if (temp.left) {
                q.push(temp.left);
            }

            if (temp.right) {
                q.push(temp.right);
            }
        }

        return sum;
    }
}

// driver code
function main() {

    let root = new Node(15);
    root.left = new Node(10);
    root.right = new Node(20);
    root.left.left = new Node(8);
    root.left.right = new Node(12);
    root.right.left = new Node(16);
    root.right.right = new Node(25);

    let obj = new Solution();
    console.log("Sum of all elements in the binary tree is:", obj.sumBT(root));
}

main();

Output
Sum of all elements in the binary tree is: 106

Time Complexity: O(n)
Auxiliary Space: O(n)

Using Morris Traversal - O(n) Time O(1) Space

Morris Traversal visits nodes without recursion or a stack by creating temporary links. If a node has no left child, add its value and move right. Otherwise, create or remove a link with its inorder predecessor to traverse left and then back. This ensures all nodes are visited once using O(1) extra space.

Let us understand with an example:

Input: root = [15, 10, 20, 8, 12, 16, 25]

Start from 15 -> left exists, create link -> move left

  • At 10 -> left exists, create link -> move left
  • At 8 -> no left child, add -> sum = 8
  • Back to 10 -> remove link, add -> sum = 18
  • At 12 -> no left child, add -> sum = 30
  • Back to 15 -> remove link, add -> sum = 45
  • At 20 -> left exists, create link -> move left
  • At 16 -> no left child, add -> sum = 61
  • Back to 20 -> remove link, add -> sum = 81
  • At 25 -> no left child, add -> sum = 106

All nodes are visited once. Final sum = 106

C++
// Program to find sum of all nodes using Morris Traversal
#include <bits/stdc++.h>
using namespace std;

// Definition for Node
class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = right = nullptr;
    }
};

int sumBT(Node *root)
{

    long int sum = 0;

    // Traverse the tree using Morris Traversal
    while (root != nullptr)
    {

        // If there is no left child, add
        // the value of the current node
        // to the sum and move to the
        // right child
        if (root->left == nullptr)
        {
            sum += root->data;
            root = root->right;
        }
        else
        {
            // Find inorder predecessor
            Node *prev = root->left;
            
            // Find the rightmost node
            // in the left subtree of
            // the current node
            while (prev->right != nullptr && prev->right != root)
            {
                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->data;
                root = root->right;
            }
        }
    }

    return sum;
}

// Driver code
int main()
{
    Node *root = new Node(15);
    root->left = new Node(10);
    root->right = new Node(20);
    root->left->left = new Node(8);
    root->left->right = new Node(12);
    root->right->left = new Node(16);
    root->right->right = new Node(25);

    cout << "Sum of all nodes in the binary tree is " << sumBT(root);

    return 0;
}
C
// Program to find sum of all nodes using Morris Traversal
#include <stdio.h>
#include <stdlib.h>

// Definition for Node 
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(int val) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = val;
    node->left = node->right = NULL;
    return node;
}

// Function to find sum using Morris Traversal 
int sumBT(struct Node* root) {

    long int sum = 0;

    while (root != NULL) {

        if (root->left == NULL) {
            sum += root->data;
            root = root->right;
        }
        else {
            struct Node* prev = root->left;

            while (prev->right != NULL && prev->right != root) {
                prev = prev->right;
            }

            if (prev->right == NULL) {
                prev->right = root;
                root = root->left;
            }
            else {
                prev->right = NULL;
                sum += root->data;
                root = root->right;
            }
        }
    }

    return sum;
}

// Driver code 
int main()
{
    struct Node* root = newNode(15);
    root->left = newNode(10);
    root->right = newNode(20);
    root->left->left = newNode(8);
    root->left->right = newNode(12);
    root->right->left = newNode(16);
    root->right->right = newNode(25);

    printf("Sum of all nodes in the binary tree is %d", sumBT(root));

    return 0;
}
Java
import java.util.*;

// Definition for Node
class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

public class GfG {
    
    static int sumBT(Node root) {
        long sum = 0;

        // Traverse the tree using Morris Traversal
        while (root!= null) {

            // If left child is NULL, process current node
            if (root.left == null) {
                sum += root.data;
                root = root.right;
            } else {
                // Find inorder predecessor
                Node prev = root.left;

                while (prev.right!= null && prev.right!= root) {
                    prev = prev.right;
                }

                // Make temporary link
                if (prev.right == null) {
                    prev.right = root;
                    root = root.left;
                } else {
                    // Remove temporary link and process node
                    prev.right = null;
                    sum += root.data;
                    root = root.right;
                }
            }
        }

        return (int) sum;
    }

    public static void main(String[] args) {
        Node root = new Node(15);
        root.left = new Node(10);
        root.right = new Node(20);
        root.left.left = new Node(8);
        root.left.right = new Node(12);
        root.right.left = new Node(16);
        root.right.right = new Node(25);

        System.out.println("Sum of all nodes in the binary tree is " + sumBT(root));
    }
}
Python
# Program to find sum of all nodes using Morris Traversal

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

class Solution:
    def sumBT(self, root):

        sum = 0

        while root is not None:

            if root.left is None:
                sum += root.data
                root = root.right
            else:
                prev = root.left

                while prev.right is not None and prev.right != root:
                    prev = prev.right

                if prev.right is None:
                    prev.right = root
                    root = root.left
                else:
                    prev.right = None
                    sum += root.data
                    root = root.right

        return sum


# Driver code
def main():
    root = Node(15)
    root.left = Node(10)
    root.right = Node(20)
    root.left.left = Node(8)
    root.left.right = Node(12)
    root.right.left = Node(16)
    root.right.right = Node(25)

    obj = Solution()
    print("Sum of all nodes in the binary tree is", obj.sumBT(root))


if __name__ == "__main__":
    main()
C#
using System;


public class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {
    
    public static int sumBT(Node root) {

        long sum = 0;

        while (root != null) {

            if (root.left == null) {
                sum += root.data;
                root = root.right;
            }
            else {
                Node prev = root.left;

                while (prev.right != null && prev.right != root) {
                    prev = prev.right;
                }

                if (prev.right == null) {
                    prev.right = root;
                    root = root.left;
                }
                else {
                    prev.right = null;
                    sum += root.data;
                    root = root.right;
                }
            }
        }

        return (int)sum;
    }

    static void Main() {

        Node root = new Node(15);
        root.left = new Node(10);
        root.right = new Node(20);
        root.left.left = new Node(8);
        root.left.right = new Node(12);
        root.right.left = new Node(16);
        root.right.right = new Node(25);

        Console.WriteLine("Sum of all nodes in the binary tree is " + sumBT(root));
    }
}
JavaScript
/* Program to find sum of all nodes using Morris Traversal */

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

class Solution {
    sumBT(root) {

        let sum = 0;

        while (root !== null) {

            if (root.left === null) {
                sum += root.data;
                root = root.right;
            }
            else {
                let prev = root.left;

                while (prev.right !== null && prev.right !== root) {
                    prev = prev.right;
                }

                if (prev.right === null) {
                    prev.right = root;
                    root = root.left;
                }
                else {
                    prev.right = null;
                    sum += root.data;
                    root = root.right;
                }
            }
        }

        return sum;
    }
}

// driver code
function main() {

    let root = new Node(15);
    root.left = new Node(10);
    root.right = new Node(20);
    root.left.left = new Node(8);
    root.left.right = new Node(12);
    root.right.left = new Node(16);
    root.right.right = new Node(25);

    let obj = new Solution();
    console.log("Sum of all nodes in the binary tree is", obj.sumBT(root));
}

main();

Output
Sum of all nodes in the binary tree is 106

Time Complexity: O(n) , Because of  all the nodes are traversing only once.
Auxiliary Space: O(1)

Comment