-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1302_Deepest_Leaves_Sum.java
More file actions
34 lines (29 loc) · 919 Bytes
/
1302_Deepest_Leaves_Sum.java
File metadata and controls
34 lines (29 loc) · 919 Bytes
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
/*
* 1302. Deepest Leaves Sum
* Problem Link: https://leetcode.com/problems/deepest-leaves-sum/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public int deepestLeavesSum(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int sum = 0;
while (!q.isEmpty()) {
sum = 0;
// for all nodes at this level
for (int count = q.size(); count > 0; count--) {
TreeNode n = q.poll();
sum += n.val;
// add children to queue (for next level)
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
}
return sum;
}
}