Maximum Level Sum of a Binary Tree

 Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.


Return the smallest level x such that the sum of all the values of nodes at level x is maximal.


 


Example 1:



Input: root = [1,7,0,7,-8,null,null]

Output: 2

Explanation: 

Level 1 sum = 1.

Level 2 sum = 7 + 0 = 7.

Level 3 sum = 7 + -8 = -1.

So we return the level with the maximum sum which is level 2.

Example 2:


Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]

Output: 2

 /**

 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxLevelSum(TreeNode root) {
         if (root == null) return 0;

        // Queue for level order traversal
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        int level = 0;               // Current level (starts from 0)
        int maxLevel = 0;            // To store the final answer (1-based index)
        int maxSum = Integer.MIN_VALUE;  // Initially very small

        // Start level-order traversal
        while (!q.isEmpty()) {
            level++;  // Increment level (root is at level 1)
            int size = q.size();  // Number of nodes in current level
            int levelSum = 0;     // Sum of nodes at current level

            // Process all nodes at the current level
            for (int i = 0; i < size; i++) {
                TreeNode curr = q.poll();       // Remove front node
                levelSum += curr.val;      // Add its value to level sum

                // Add left and right children to queue
                if (curr.left != null) {
                    q.offer(curr.left);
                }
                if (curr.right != null) {
                    q.offer(curr.right);
                }
            }

            // Check if this level has the highest sum so far
            if (levelSum > maxSum) {
                maxSum = levelSum;   // Update max sum
                maxLevel = level;    // Update level number
            }
        }

        return maxLevel;  // Return the level with maximum sum
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence