[LeetCode] Kth Largest Sum in a Binary Tree

2583. Kth Largest Sum in a Binary Tree

You are given the root of a binary tree and a positive integer k.

The level sum in the tree is the sum of the values of the nodes that are on the same level.

Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1.

Note that two nodes are on the same level if they have the same distance from the root.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<int, long long> sum;
void dfs(TreeNode* node, int level) {
if(!node) return;
sum[level] += node->val;
dfs(node->left, level + 1);
dfs(node->right, level + 1);
}
public:
long long kthLargestLevelSum(TreeNode* root, int k) {
dfs(root,0);
if(sum.size() < k) return -1;
vector<long long> S;
for(auto [k,v] : sum) S.push_back(v);
sort(rbegin(S), rend(S));
return S[k-1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/05/PS/LeetCode/kth-largest-sum-in-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.