코딩테스트

[leetcode] 1161. Maximum Level Sum of a Binary Tree

nayoon 2024. 6. 14. 01:41

 

문제

 

/**
 * 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 Map<Integer, Integer> map;
    public int max;
    public int maxLevelSum(TreeNode root) {
        map = new HashMap<>();
        max = 0;
        count(root, 1);

        int maxValue = Integer.MIN_VALUE;
        int maxIndex = 0;
        for(int i = 1; i <= max; i++) {
            if (maxValue < map.get(i)) {
                maxValue = map.get(i);
                maxIndex = i;
            }
        }
        
        return maxIndex;
    }

    public void count(TreeNode node, int level) {
        if (node == null) {
            return;
        }

        if (max < level) {
            max = level;
        }

        map.put(level, map.getOrDefault(level, 0) + node.val);

        count(node.left, level + 1);
        count(node.right, level + 1);
    }
}