Given a Binary Tree, write a function getLevelDiff which returns the difference between the sum of nodes at odd level and the sum of nodes at even level
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
Example:
for, the above tree the odd level sum is 3 (root itself) and even level sum is 10 (leaf nodes here) thus the difference is 3-10=-7
Algorithm:
We solve the problem with help of level order traversal.
Function getLevelDiff( Node* root)
1. Initialize two flags, one for even level & other for odd levels.
falgo is initialized to 1 because we are starting with root which is considered to be odd level.
2. Initialize two variables, one to store sum of all odd levels & other to store sum of all even levels.
3. Do a level order traversal being conscious about current level whether odd or even. We can do this using the flags. When flage=1 and flago=0 we are at an even level. So we add the traversed node values with sume. When flago=1 and flage=0 we are at an odd level. So we add the traversed node values with sumo.
We every time push NULL at end of each level & swap values between the flags at end of each level. For example when root is processed (odd level) & we encounter a NULL, we change flage from 0 to 1, flago from 1 to 0 as we are gong to process a even level now
Finally we achieve both the sums.
4. Return sumo-sume
Pseudo code:
C++ implementation
Output
Example with explanation