Skip to content

Commit 6c5989b

Browse files
authored
Create kth-largest-sum-in-a-binary-tree.cpp
1 parent 7af2398 commit 6c5989b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
// bfs, quick select
5+
class Solution {
6+
public:
7+
long long kthLargestLevelSum(TreeNode* root, int k) {
8+
vector<int64_t> arr;
9+
vector<TreeNode *> q = {root};
10+
while (!empty(q)) {
11+
vector<TreeNode *> new_q;
12+
for (const auto& u : q) {
13+
if (u->left) {
14+
new_q.emplace_back(u->left);
15+
}
16+
if (u->right) {
17+
new_q.emplace_back(u->right);
18+
}
19+
}
20+
arr.emplace_back(accumulate(cbegin(q), cend(q), 0LL, [](const auto& total, const auto& node) {
21+
return total + node->val;
22+
}));
23+
q = move(new_q);
24+
}
25+
if (k - 1 >= size(arr)) {
26+
return -1;
27+
}
28+
nth_element(begin(arr), begin(arr) + (k - 1), end(arr), greater<int64_t>());
29+
return arr[k - 1];
30+
}
31+
};

0 commit comments

Comments
 (0)