79
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.
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.
- 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.
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