LeetCode 1302. Deepest Leaves Sum
原题链接在这里:https://leetcode.com/problems/deepest-leaves-sum/
题目:
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
题解:
Perform level order traversal.
For each leavel, reset result to 0, and then accumlate this level sum.
When queue is empty, the res is the sum of last level sum.
Time Complexity: O(n). n is number of nodes in the tree.
Space: O(n).
AC 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 if(root == null){ 19 return 0; 20 } 21 22 LinkedList<TreeNode> que = new LinkedList<>(); 23 que.add(root); 24 int res = 0; 25 while(!que.isEmpty()){ 26 int size = que.size(); 27 res = 0; 28 while(size-- > 0){ 29 TreeNode cur = que.poll(); 30 res += cur.val; 31 if(cur.left != null){ 32 que.add(cur.left); 33 } 34 35 if(cur.right != null){ 36 que.add(cur.right); 37 } 38 } 39 } 40 41 return res; 42 } 43 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 想让你多爱自己一些的开源计时器
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
2017-09-29 LeetCode 486. Predict the Winner
2017-09-29 LeetCode 416. Partition Equal Subset Sum
2015-09-29 LeetCode 216. Combination Sum III