-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_1161.java
More file actions
32 lines (31 loc) · 1.04 KB
/
Copy pathproblem_1161.java
File metadata and controls
32 lines (31 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
1161. 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. */
class Solution {
public int maxLevelSum(TreeNode root) {
Deque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
int sum = Integer.MIN_VALUE, check_sum = 0, cal = 0, ans = 0;
while(!queue.isEmpty()){
int length = queue.size();
cal += 1;
for(int i=0;i<length;i++){
TreeNode node = queue.poll();
check_sum += node.val;
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
if(check_sum > sum){
sum = check_sum;
ans = cal;
}
check_sum = 0;
}
return ans;
}
}