Q. Program to calculate the difference between the sum of the odd level and even level nodes of a Binary Tree.

Explanation

In this program, we need to calculate the difference between the sum of nodes present at odd levels and sum of nodes present at even levels. Suppose, if a tree contains 5 levels, then

Program to calculate the difference between the sum of the odd level and even level nodes of a Binary Tree

In the above diagram, odd levels are represented using blue dotted lines and even with green.

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, Assign the data part of a node with an appropriate value having its left and right child as NULL.
  3. Define another class which has an attribute root.
    1. Root represents the root node of the tree having null value initially.
  4. The difference() will calculate the difference between the sum of nodes at the odd and even levels:
    1. Traverse through the binary tree level wise using Queues.
    2. Keep track of current level using the variable currentLevel.
    3. If the currentLevel is divisible by 2, then add all the values of nodes present in currentLevel to variable evenLevel. Else, add all the values of nodes to variable oddLevel.
    4. Calculate the difference by subtracting value present in evenLevel from oddLevel.

Solution

Python

Output:

Difference between sum of odd level and even level nodes: 11

C

Output:

Difference between sum of odd level and even level nodes: 11

JAVA

Output:

Difference between sum of odd level and even level nodes: 11

C#

Output:

Difference between sum of odd level and even level nodes: 11

PHP

Output:

Difference between sum of odd level and even level nodes: 11

Next TopicPrograms List




Latest Courses