Skip to content

Commit 15c0847

Browse files
committed
feat(leetcode): add No.1161
1 parent a19f894 commit 15c0847

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/
2+
//
3+
// algorithms
4+
// Easy (72.24%)
5+
// Total Accepted: 3,412
6+
// Total Submissions: 4,723
7+
// beats 100.0% of java submissions
8+
9+
/**
10+
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
11+
* left; TreeNode right; TreeNode(int x) { val = x; } }
12+
*/
13+
class Solution {
14+
public int maxLevelSum(TreeNode root) {
15+
LinkedList<TreeNode> q = new LinkedList<>();
16+
q.offer(root);
17+
q.offer(null);
18+
19+
int levelSum = 0, maxSum = Integer.MIN_VALUE;
20+
int level = 1, res = 1;
21+
22+
while (true) {
23+
TreeNode curNode = q.pollFirst();
24+
if (curNode == null) {
25+
if (levelSum > maxSum) {
26+
maxSum = levelSum;
27+
res = level;
28+
}
29+
if (q.size() == 0) {
30+
break;
31+
}
32+
q.offer(null);
33+
levelSum = 0;
34+
level++;
35+
} else {
36+
levelSum += curNode.val;
37+
if (curNode.left != null) {
38+
q.offer(curNode.left);
39+
}
40+
41+
if (curNode.right != null) {
42+
q.offer(curNode.right);
43+
}
44+
}
45+
}
46+
47+
return res;
48+
}
49+
}

0 commit comments

Comments
 (0)