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 @ 2022-09-29 16:25  Dylan_Java_NYC  阅读(21)  评论(0编辑  收藏  举报