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 }
复制代码

类似Binary Tree Level Order Traversal.

posted @   Dylan_Java_NYC  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 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
点击右上角即可分享
微信分享提示