Maximum Level Sum of a Binary Tree - LeetCode
이진 트리의 루트 노드가 주어질 때, 각 레벨에 있는 노드 값의 합이 최대인 레벨 x를 반환합니다.
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
문제 요약:
주어진 이진 트리에서 각 레벨의 노드 값 합이 최대인 레벨을 찾는 문제입니다.
풀이 과정:
class Solution {
public int maxLevelSum(TreeNode root) {
if (root == null) return 0;
int maxSum = Integer.MIN_VALUE;
int maxLvl = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int lvl = 0;
while(!queue.isEmpty()){
int queSize = queue.size();
int sum = 0;
lvl++;
for(int i = 0; i < queSize; i++){
TreeNode node = queue.poll();
sum += node.val;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
if(sum > maxSum){
maxSum = sum;
maxLvl = lvl;
}
}
return maxLvl;
}
}
450. Delete Node in a BST (0) | 2023.10.29 |
---|---|
700. Search in a Binary Search Tree (0) | 2023.10.29 |
199. Binary Tree Right Side View (0) | 2023.10.29 |
1207. Unique Number of Occurrences (0) | 2023.10.29 |
2215. Find the Difference of Two Arrays (0) | 2023.10.29 |