forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathdeepest-leaves-sum.cpp
More file actions
32 lines (31 loc) · 864 Bytes
/
deepest-leaves-sum.cpp
File metadata and controls
32 lines (31 loc) · 864 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Time: O(n)
// Space: O(w)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
vector<TreeNode *> curr = {root}, prev;
while (!curr.empty()) {
prev = move(curr);
for (const auto& p : prev) {
for (const auto& child : {p->left, p->right}) {
if (child) {
curr.emplace_back(child);
}
}
}
}
return accumulate(prev.cbegin(), prev.cend(), 0,
[](const auto& x, const auto& y) {
return x + y->val;
});
}
};