Given a Binary Tree having positive and negative nodes, the task is to find the maximum absolute difference of level sum in it.
Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 9 Explanation: Sum of all nodes of 0 level is 4 Sum of all nodes of 1 level is -3 Sum of all nodes of 2 level is 6 Hence maximum absolute difference of level sum = 9 (6 - (-3)) Input: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 Output: 16
Approach: To find the maximum absolute difference of level sum, we only need to find Maximum level sum and Minimum level sum because absolute difference of maximum and minimum level sum always gives us Maximum absolute difference, i.e.
Maximum absolute difference = abs(Maximum level sum – Minimum level sum)
Below are the steps for algorithm of above observation:
- The idea is to do level order traversal of the tree.
- While doing traversal, process nodes of different levels separately.
- For every level being processed, compute sum of nodes in the level and keep track of maximum and minimum level sum.
- Then return the absolute difference of maximum and minimum level sum.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Difference between sums of odd level and even level nodes of a Binary Tree
- Find maximum level sum in Binary Tree
- Find maximum level product in Binary Tree
- Find Maximum Level Sum in Binary Tree using Recursion
- Find the maximum node at a given level in a binary tree
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Difference between sums of odd position and even position nodes for each level of a Binary Tree
- Maximum difference between node and its ancestor in Binary Tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Sum of all nodes at Kth level in a Binary Tree
- Largest value in each level of Binary Tree
- Smallest value in each level of Binary Tree
- Get Level of a node in a Binary Tree
- Swap Nodes in Binary tree of every k'th level
- Nodes at Kth level without duplicates in a Binary Tree
- Insertion in a Binary Tree in level order
- Height of binary tree considering even level leaves only
- Level with maximum number of nodes using DFS in a N-ary tree
- Boundary Level order traversal of a Binary Tree