// Program to print sum of all the elements of a binary tree /#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};intsumBT(Node*root){if(root==NULL)return0;return(root->data+sumBT(root->left)+sumBT(root->right));}// Driver codeintmain(){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);intsum=sumBT(root);cout<<"Sum of all the elements is: "<<sum<<endl;return0;}
C
// Program to print sum of all the elements of a binary tree #include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};structNode*newNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->left=node->right=NULL;returnnode;}// Function to find sum of all elements intsumBT(structNode*root){if(root==NULL)return0;return(root->data+sumBT(root->left)+sumBT(root->right));}// Driver code intmain(){structNode*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);intsum=sumBT(root);printf("Sum of all the elements is: %d\n",sum);return0;}
Java
/* Program to print sum of all the elements of a binary tree */importjava.util.*;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}publicclassGfG{publicstaticintsumBT(Noderoot){if(root==null)return0;return(root.data+sumBT(root.left)+sumBT(root.right));}publicstaticvoidmain(String[]args){Noderoot=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);intsum=sumBT(root);System.out.println("Sum of all the elements is: "+sum);}}
Python
# Program to print sum of all the elements of a binary treeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NoneclassSolution:defsumBT(self,root):ifrootisNone:return0return(root.data+self.sumBT(root.left)+self.sumBT(root.right))# Driver codedefmain():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#
usingSystem;usingSystem.Collections.Generic;// Definition for NodepublicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGfG{publicstaticintsumBT(Noderoot){if(root==null)return0;return(root.data+sumBT(root.left)+sumBT(root.right));}staticvoidMain(){Noderoot=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);intsum=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 */classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}classSolution{sumBT(root){if(root===null)return0;return(root.data+this.sumBT(root.left)+this.sumBT(root.right));}}// driver codefunctionmain(){letroot=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);letobj=newSolution();letsum=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>usingnamespacestd;// Definition for NodeclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};intsumBT(Node*root){//sum variable to track the sum of//all variables.intsum=0;queue<Node*>q;// push root nodeq.push(root);// iterate level order traversalwhile(!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 childif(temp->left){q.push(temp->left);}// push right childif(temp->right){q.push(temp->right);}}returnsum;}// Driver code /intmain(){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);cout<<"Sum of all elements in the binary tree is: "<<sumBT(root);return0;}
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 structNode{intdata;structNode*left;structNode*right;};structNode*newNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->left=node->right=NULL;returnnode;}// Queue implementation structQueue{structNode*arr[1000];intfront,rear;};voidinit(structQueue*q){q->front=q->rear=0;}voidpush(structQueue*q,structNode*node){q->arr[q->rear++]=node;}structNode*pop(structQueue*q){returnq->arr[q->front++];}intisEmpty(structQueue*q){returnq->front==q->rear;}// Function to find sum of all elements intsumBT(structNode*root){intsum=0;structQueueq;init(&q);push(&q,root);while(!isEmpty(&q)){structNode*temp=pop(&q);sum+=temp->data;if(temp->left){push(&q,temp->left);}if(temp->right){push(&q,temp->right);}}returnsum;}// Driver code intmain(){structNode*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));return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;// Definition for NodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}publicclassGfG{publicstaticintsumBT(Noderoot){// sum variable to store total sumintsum=0;Queue<Node>q=newLinkedList<>();// push root nodeq.add(root);// iterate level order traversalwhile(!q.isEmpty()){Nodetemp=q.poll();// add node data to sumsum+=temp.data;// push left childif(temp.left!=null){q.add(temp.left);}// push right childif(temp.right!=null){q.add(temp.right);}}returnsum;}publicstaticvoidmain(String[]args){Noderoot=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);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 TraversalfromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NoneclassSolution:defsumBT(self,root):sum=0q=deque()q.append(root)whileq:temp=q.popleft()sum+=temp.dataiftemp.left:q.append(temp.left)iftemp.right:q.append(temp.right)returnsum# Driver codedefmain():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#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGfG{publicstaticintsumBT(Noderoot){intsum=0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodetemp=q.Dequeue();sum+=temp.data;if(temp.left!=null){q.Enqueue(temp.left);}if(temp.right!=null){q.Enqueue(temp.right);}}returnsum;}staticvoidMain(){Noderoot=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);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 classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}classSolution{sumBT(root){letsum=0;letq=[];q.push(root);while(q.length>0){lettemp=q.shift();sum+=temp.data;if(temp.left){q.push(temp.left);}if(temp.right){q.push(temp.right);}}returnsum;}}// driver codefunctionmain(){letroot=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);letobj=newSolution();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>usingnamespacestd;// Definition for NodeclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};intsumBT(Node*root){longintsum=0;// Traverse the tree using Morris Traversalwhile(root!=nullptr){// If there is no left child, add// the value of the current node// to the sum and move to the// right childif(root->left==nullptr){sum+=root->data;root=root->right;}else{// Find inorder predecessorNode*prev=root->left;// Find the rightmost node// in the left subtree of// the current nodewhile(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 childprev->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// childprev->right=nullptr;sum+=root->data;root=root->right;}}}returnsum;}// Driver codeintmain(){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);cout<<"Sum of all nodes in the binary tree is "<<sumBT(root);return0;}
C
// Program to find sum of all nodes using Morris Traversal#include<stdio.h>#include<stdlib.h>// Definition for Node structNode{intdata;structNode*left;structNode*right;};structNode*newNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->left=node->right=NULL;returnnode;}// Function to find sum using Morris Traversal intsumBT(structNode*root){longintsum=0;while(root!=NULL){if(root->left==NULL){sum+=root->data;root=root->right;}else{structNode*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;}}}returnsum;}// Driver code intmain(){structNode*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));return0;}
Java
importjava.util.*;// Definition for NodeclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassGfG{staticintsumBT(Noderoot){longsum=0;// Traverse the tree using Morris Traversalwhile(root!=null){// If left child is NULL, process current nodeif(root.left==null){sum+=root.data;root=root.right;}else{// Find inorder predecessorNodeprev=root.left;while(prev.right!=null&&prev.right!=root){prev=prev.right;}// Make temporary linkif(prev.right==null){prev.right=root;root=root.left;}else{// Remove temporary link and process nodeprev.right=null;sum+=root.data;root=root.right;}}}return(int)sum;}publicstaticvoidmain(String[]args){Noderoot=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);System.out.println("Sum of all nodes in the binary tree is "+sumBT(root));}}
Python
# Program to find sum of all nodes using Morris TraversalclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NoneclassSolution:defsumBT(self,root):sum=0whilerootisnotNone:ifroot.leftisNone:sum+=root.dataroot=root.rightelse:prev=root.leftwhileprev.rightisnotNoneandprev.right!=root:prev=prev.rightifprev.rightisNone:prev.right=rootroot=root.leftelse:prev.right=Nonesum+=root.dataroot=root.rightreturnsum# Driver codedefmain():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#
usingSystem;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGfG{publicstaticintsumBT(Noderoot){longsum=0;while(root!=null){if(root.left==null){sum+=root.data;root=root.right;}else{Nodeprev=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;}staticvoidMain(){Noderoot=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);Console.WriteLine("Sum of all nodes in the binary tree is "+sumBT(root));}}
JavaScript
/* Program to find sum of all nodes using Morris Traversal */classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}classSolution{sumBT(root){letsum=0;while(root!==null){if(root.left===null){sum+=root.data;root=root.right;}else{letprev=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;}}}returnsum;}}// driver codefunctionmain(){letroot=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);letobj=newSolution();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)