Skip to content

Commit 721eea8

Browse files
authored
Create deepest-leaves-sum.cpp
1 parent 152e441 commit 721eea8

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

C++/deepest-leaves-sum.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(n)
2+
// Space: O(w)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
int deepestLeavesSum(TreeNode* root) {
16+
vector<TreeNode *> curr = {root}, prev;
17+
while (!curr.empty()) {
18+
prev = move(curr);
19+
for (const auto& p : prev) {
20+
for (const auto& child : {p->left, p->right}) {
21+
if (child) {
22+
curr.emplace_back(child);
23+
}
24+
}
25+
}
26+
}
27+
return accumulate(prev.cbegin(), prev.cend(), 0,
28+
[](const auto& x, const auto& y) {
29+
return x + y->val;
30+
});
31+
}
32+
};

0 commit comments

Comments
 (0)