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
|
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]; } };
|