- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1302.java
68 lines (63 loc) · 2.1 KB
/
_1302.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.LinkedList;
importjava.util.Queue;
publicclass_1302 {
publicstaticclassSolution1 {
publicintdeepestLeavesSum(TreeNoderoot) {
intdepth = maxDepth(root);
returnbfs(root, depth);
}
privateintbfs(TreeNoderoot, intdepth) {
Queue<TreeNode> queue = newLinkedList<>();
queue.offer(root);
intcurrentLevel = 0;
intsum = 0;
while (!queue.isEmpty()) {
intsize = queue.size();
currentLevel++;
for (inti = 0; i < size; i++) {
TreeNodecurrNode = queue.poll();
if (currentLevel == depth) {
sum += currNode.val;
}
if (currNode.left != null) {
queue.offer(currNode.left);
}
if (currNode.right != null) {
queue.offer(currNode.right);
}
}
}
returnsum;
}
privateintmaxDepth(TreeNoderoot) {
if (root == null) {
return0;
}
returnMath.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
publicstaticclassSolution2 {
publicintdeepestLeavesSum(TreeNoderoot) {
Queue<TreeNode> queue = newLinkedList<>();
queue.offer(root);
intsum = 0;
while (!queue.isEmpty()) {
intsize = queue.size();
sum = 0;
for (inti = 0; i < size; i++) {
TreeNodecurr = queue.poll();
sum += curr.val;
if (curr.left != null) {
queue.offer(curr.left);
}
if (curr.right != null) {
queue.offer(curr.right);
}
}
}
returnsum;
}
}
}