Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it and print the maximum sum.
Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 6 Sum of all nodes of the 1st level is 4. Sum of all nodes of the 2nd level is -3. Sum of all nodes of the 3rd level is 6. Hence, the maximum sum is 6. Input: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 Output: 17
Approach: Find the maximum level in the given binary tree then create an array sum where sum[i] will store the sum of the elements at level i.
Now, write a recursive function that takes a node of the tree and its level as the argument and updates the sum for the current level then makes recursive calls for the children with the updated level as one more than the current level (this is because children are at a level one more than their parent). Finally, print the maximum value from the sum array.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find maximum level sum in Binary Tree
- Find maximum level product in Binary Tree
- Find the maximum node at a given level in a binary tree
- Find the node with maximum value in a Binary Search Tree using recursion
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Find if given vertical level of binary tree is sorted or not
- Find the node with minimum value in a Binary Search Tree using recursion
- Find the numbers present at Kth level of a Fibonacci Binary Tree
- Difference between sums of odd level and even level nodes of a Binary Tree
- Construct a Binary in Level Order using Recursion
- Product of nodes at k-th level in a tree represented as string using Recursion
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Find maximum vertical sum in binary tree
- Find maximum (or minimum) in Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.