LeetCode solutions

2646. Kth Largest Sum in a Binary Tree

My accepted C++ solution to LeetCode problem 2646, Kth Largest Sum in a Binary Tree, running in 66ms.

  • Difficulty: Medium
  • C++
  • Runtime 66ms
  • Memory 271.2MB

Read the problem on LeetCode View on GitHub

C++

Accepted on LeetCode — runtime 66ms, memory 271.2MB, accepted 2025-12-27.

cpp
class Solution {
    public:
    long long kthLargestLevelSum(TreeNode* root, int k) {
        vector<long long> sums;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int size = q.size();
            long long sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode* node = q.front(); q.pop();
                sum += node->val;
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            sums.push_back(sum);
        }
        if (k > sums.size()) return -1;
        sort(sums.rbegin(), sums.rend());
        return sums[k-1];
    }
};

Source