![]() |
VOOZH | about |
Given an N-ary Tree rooted at 1, the task is to find the difference between the sum of nodes at the odd level and the sum of nodes at even level.
Examples:
Input:
4
/ | \
2 3 -5
/ \ / \
-1 3 -2 6
Output: 10
Explanation:
Sum of nodes at even levels = 2 + 3 + (-5) = 0
Sum of nodes at odd levels = 4 + (-1) + 3 + (-2) + 6 = 10
Hence, the required difference is 10.Input:
1
/ | \
2 -1 3
/ \ \
4 5 8
/ / | \
2 6 12 7Output: -13
Approach: To solve the problem, the idea is to find the respective sums of the nodes at the even and odd levels using Level Order Traversal and calculate the difference between them. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
10
Time Complexity: O(N)
Auxiliary Space: O(N)