Find Maximum Level Sum in Binary Tree using Recursion
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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.