-
Notifications
You must be signed in to change notification settings - Fork 1
/
MaximumLevelSumOfABinaryTree.java
46 lines (39 loc) · 1.2 KB
/
MaximumLevelSumOfABinaryTree.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.Deque;
import java.util.LinkedList;
// https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/
public class MaximumLevelSumOfABinaryTree {
private final TreeNode input;
public MaximumLevelSumOfABinaryTree(TreeNode input) {
this.input = input;
}
public int solution() {
Deque<TreeNode> nodes = new LinkedList<>();
nodes.add(input);
int max = Integer.MIN_VALUE;
int maxLevel = 1;
int level = 1;
while (!nodes.isEmpty()) {
int size = nodes.size();
int sum = 0;
while (size != 0) {
TreeNode node = nodes.pop();
sum += node.val;
if (node.left != null) {
nodes.addLast(node.left);
}
if (node.right != null) {
nodes.addLast(node.right);
}
size--;
}
if (sum > max) {
max = sum;
maxLevel = level;
}
level++;
}
return maxLevel;
}
}