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, 104]
. 1 <= Node.val <= 100
层数最深叶子节点的和。
给你一棵二叉树的根节点 root
,请你返回层数最深的叶子节点的和。
这道题的 tag 给的是 DFS 但是这里我给一个更容易理解的 BFS 的做法吧。题目要你计算的是所有的叶子节点的节点值的和。我们可以这样做,对于每一层节点,我们去计算当前层所有节点的和。如果有下一层的话,那么我们把 res 重置为 0 即可。
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int deepestLeavesSum(TreeNode root) { 18 int res = 0; 19 Queue<TreeNode> queue = new LinkedList<>(); 20 queue.offer(root); 21 while (!queue.isEmpty()) { 22 int size = queue.size(); 23 res = 0; 24 for (int i = 0; i < size; i++) { 25 TreeNode cur = queue.poll(); 26 res += cur.val; 27 if (cur.left != null) { 28 queue.offer(cur.left); 29 } 30 if (cur.right != null) { 31 queue.offer(cur.right); 32 } 33 } 34 } 35 return res; 36 } 37 }