Q. Program to find the sum of all the nodes of a Binary Tree

Explanation

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.

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

  1. 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.
  2. When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  3. Define another class which has an attribute root.
    1. Root represents the root node of the tree and initialize it to null.
  4. calculateSum() will calculate the sum of nodes present in the binary tree:
    1. It checks whether the root is null, which means that the tree is empty.
    2. If the tree is not empty, traverse through left subtree, calculate the sum of nodes and store it in sumLeft.
    3. Then, traverse through the right subtree, calculate the sum of nodes and store it in sumRight.
    4. Finally, calculate total sum = temp.data + sumLeft + sumRight.

Solution

Python

Output:

Sum of all nodes of binary tree: 31

C

Output:

Sum of all nodes of binary tree: 31

JAVA

Output:

Sum of all nodes of binary tree: 31

C#

Output:

Sum of all nodes of binary tree: 31

PHP

Output:

Sum of all nodes of binary tree: 31

Next TopicPrograms List




Latest Courses