Javatpoint Logo
Javatpoint Logo

Java program to find the sum of all the nodes of a binary tree

In this program, we need to calculate the sum of nodes present in the binary tree. First, we will traverse through the left sub-tree and calculate the sum of nodes present in the left sub-tree. Similarly, we calculate the sum of nodes present in the right sub-tree and calculate total sum by adding the root?s data.

Java program to find the sum of all the nodes of a binary tree

For the given tree, sum of nodes of the binary tree will be 1 + 2 + 5 + 8 + 6 + 9 = 31.

Algorithm

  • Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
  • When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  • Define another class which has an attribute root.
    • Root represents the root node of the tree and initialize it to null.

a. calculateSum() will calculate the sum of nodes present in the binary tree:

  • It checks whether the root is null, which means that the tree is empty.
  • If the tree is not empty, traverse through left subtree, calculate the sum of nodes and store it in sumLeft.
  • Then, traverse through the right subtree, calculate the sum of nodes and store it in sumRight.
  • Finally, calculate total sum = temp.data + sumLeft + sumRight.

Program:

Output:

Sum of all nodes of binary tree: 31
Next TopicJava Programs





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA