Find the sum of all elements in Binary Tree

By | July 16, 2020

In this post, We will learn How to write a Java program to find the sum of all elements in Binary Tree?

For Example, the Sum of all elements in Binary Tree of below Image :

1+2+3+4+5+6+7 = 28

Binary Tree Example

Recursive Approach:

We call recursively, left subtree sum, right subtree sum, and add their values to the current note’s value.

 

Time Complexity : O(n) , Space Complexity : O(n) for recusive Stack 

Iterative Approach:

We can use level order traversal with a simple change. Every time after deleting an element from Queue, add the note’s value to sum variable.

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

Below is the Complete Source code: 

Sum Of All Elements In BinaryTree

 

BinaryTree.java

 

ClientTest.java

The output of This Program:

Calling the Recursive Method…
Sum of All Elements:28
Calling the Iterative Method…
Sum of All Elements:28

You May Also Like:

Introduction to Tree Data Structure
Introduction to Binary Tree
Difference between binary and binary search trees
Structure of Binary Trees
Operations and use of Binary Trees
Insert operation in a binary search tree
Delete operation in a binary search tree
Search operation in a binary search tree
Binary Tree Traversals
PreOrder traversal of binary tree implementation in Java
InOrder traversal of binary tree implementation in Java
PostOrder traversal of binary tree implementation in Java
Find the node with minimum and maximum values in a Binary Search Tree
Find a mirror image of a binary tree
How do you find if two given binary trees are the same or identical

That’s all about How to write a Java program to find the sum of all elements in Binary Tree?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.