How to Find Sum of Nodes in a Binary Tree in C++

In this article, we will learn how to find the sum of nodes in a binary tree in C++.

Example

Input:
            8
           / \
          7   6
         / \ / \
        5  4 3  2
Output: 35
Exaplnation: 8+7+6+5+4+3+2 = 35

Sum of Nodes in Binary Tree in C++

We are going this solve this problem using a recursive approach.

1. Firstly, create a tree using struct.

2. Now start to add the root node and recursive call left subtree and then recursive call the right sum tree until no leaf node is found.

3. Finally, return the sum of nodes.

#include <bits/stdc++.h>
using namespace std;

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

Node *newNode(int data){
    Node* node = new Node;
    node->data = data;
    node->right = node->left = NULL;
    return node;
}
void inorder(Node* root){
    if (root == NULL)
    return;

    inorder(root->left);
    cout<<root->data<<" ";
    inorder(root->right);
}
int SumOfNodes(Node *root){
    if (root == NULL)
    return 0;

    return (root->data + SumOfNodes(root->left) + SumOfNodes(root->right));
}
int main(){
    Node* root = newNode(8);
    root->left = newNode(7);
    root->right = newNode(6);
    root->left->left = newNode(5);
    root->left->right = newNode(4);
    root->right->left = newNode(3);
    root->right->right = newNode(2);
    cout<<"The inorder of the given binary tree is: ";
    inorder(root);
    cout<<endl;
    cout<<"Sum of nodes: "<<SumOfNodes(root);;
    return 0;
}

Output

The inorder of the given binary tree is: 5 7 4 8 3 6 2 
Sum of nodes: 35

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *