1302. Deepest Leaves Sum (M)
Deepest Leaves Sum (M)
题目
Given the root
of a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
Example 2:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]
. 1 <= Node.val <= 100
题意
计算二叉树最后一层结点的和。
思路
直接层序遍历。
代码实现
Java
class Solution {
public int deepestLeavesSum(TreeNode root) {
if (root == null) return 0;
int sum = 0;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
sum = 0;
int size = q.size();
while (size > 0) {
TreeNode cur = q.poll();
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
sum += cur.val;
size--;
}
}
return sum;
}
}