Skip to content

Commit 319a0a0

Browse files
committed
day 11
1 parent bd9cc07 commit 319a0a0

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Deepest Leaves Sum
3+
==================
4+
5+
Given the root of a binary tree, return the sum of values of its deepest leaves.
6+
7+
Example 1:
8+
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
9+
Output: 15
10+
11+
Example 2:
12+
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
13+
Output: 19
14+
15+
Constraints:
16+
The number of nodes in the tree is in the range [1, 104].
17+
1 <= Node.val <= 100
18+
19+
Hint #1
20+
Traverse the tree to find the max depth.
21+
22+
Hint #2
23+
Traverse the tree again to compute the sum required.
24+
*/
25+
26+
/**
27+
* Definition for a binary tree node.
28+
* struct TreeNode {
29+
* int val;
30+
* TreeNode *left;
31+
* TreeNode *right;
32+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
33+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
34+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
35+
* };
36+
*/
37+
38+
class Solution
39+
{
40+
public:
41+
int deepestLeavesSum(TreeNode *root)
42+
{
43+
int ans = 0;
44+
queue<TreeNode *> pending;
45+
pending.push(root);
46+
47+
while (pending.size())
48+
{
49+
int size = pending.size();
50+
int curr_ans = 0;
51+
for (int i = 0; i < size; ++i)
52+
{
53+
auto curr = pending.front();
54+
pending.pop();
55+
curr_ans += curr->val;
56+
if (curr->left)
57+
pending.push(curr->left);
58+
if (curr->right)
59+
pending.push(curr->right);
60+
}
61+
ans = curr_ans;
62+
}
63+
return ans;
64+
}
65+
};

Leetcode Daily Challenge/April-2021/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@
1212
| 8. | [Letter Combinations of a Phone Number](https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/594/week-2-april-8th-april-14th/3701/) | [cpp](./08.%20Letter%20Combinations%20of%20a%20Phone%20Number.cpp) |
1313
| 9. | [Verifying an Alien Dictionary](https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/594/week-2-april-8th-april-14th/3702/) | [cpp](./09.%20Verifying%20an%20Alien%20Dictionary.cpp) |
1414
| 10. | [Longest Increasing Path in a Matrix](https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/594/week-2-april-8th-april-14th/3703/) | [cpp](./10.%20Longest%20Increasing%20Path%20in%20a%20Matrix.cpp) |
15+
| 11. | [Deepest Leaves Sum](https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/594/week-2-april-8th-april-14th/3704/) | [cpp](./11.%20Deepest%20Leaves%20Sum.cpp) |

0 commit comments

Comments
 (0)