publicintdeepestLeavesSum(TreeNode root){int sum =0;Queue<TreeNode> q =newLinkedList<>();
q.offer(root);while(!q.isEmpty()){int size = q.size();
sum =0;for(int i =0; i < size; i++){TreeNode cur = q.poll();
sum += cur.val;if(cur.left !=null) q.offer(cur.left);if(cur.right !=null) q.offer(cur.right);}}return sum;}
方法2:DFS
int maxDepth =-1, res =0;publicintdeepestLeavesSum(TreeNode root){dfs(root,0);return res;}privatevoiddfs(TreeNode cur,int depth){if(cur ==null)return;dfs(cur.left, depth +1);if(depth >= maxDepth){if(depth > maxDepth) res =0;
maxDepth = depth;
res += cur.val;}dfs(cur.right, depth +1);}