Given a binary tree, calculate the difference between the sum of all nodes present at odd levels and the sum of all nodes present at even level.

For example, consider the following binary tree. The required difference is:

(1 + 4 + 5 + 6) - (2 + 3 + 7 + 8) = -4

 
Difference between sum of binary tree nodes

Practice this problem

The idea is to traverse the tree and pass the level of each node in recursion. We also pass a variable to store the required difference. If the node’s level is odd, increase the difference by the node’s value; otherwise, decrease the difference by the same amount. At the end of the recursion, the variable will contain the required difference.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

-4

Java


Download  Run Code

Output:

-4

Python


Download  Run Code

Output:

-4

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.