题目

Given the root of a binary tree, return the sum of values of its deepest leaves.

Example 1:

image.png

  1. Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
  2. Output: 15

Example 2:

  1. Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
  2. Output: 19

Constraints:

  • The number of nodes in the tree is in the range [1, 10^4].
  • 1 <= Node.val <= 100

题意

计算二叉树最后一层结点的和。

思路

直接层序遍历。


代码实现

Java

  1. class Solution {
  2. public int deepestLeavesSum(TreeNode root) {
  3. if (root == null) return 0;
  4. int sum = 0;
  5. Queue<TreeNode> q = new LinkedList<>();
  6. q.offer(root);
  7. while (!q.isEmpty()) {
  8. sum = 0;
  9. int size = q.size();
  10. while (size > 0) {
  11. TreeNode cur = q.poll();
  12. if (cur.left != null) q.offer(cur.left);
  13. if (cur.right != null) q.offer(cur.right);
  14. sum += cur.val;
  15. size--;
  16. }
  17. }
  18. return sum;
  19. }
  20. }