> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Kth Largest Sum in a Binary Tree

> Tested Python solution for LeetCode 2583 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 2583, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Breadth-First Search](/catalog/topics/breadth-first-search), [Sorting](/catalog/topics/sorting), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2583   # by problem number
lcpy gen -s kth_largest_sum_in_a_binary_tree   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2022/12/14/binaryytreeedrawio-2.png)

```
Input: root = [5,8,9,2,1,3,7,4,6], k = 2
Output: 13
Explanation: The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2nd largest level sum is 13.
```

![Example 2](https://assets.leetcode.com/uploads/2022/12/14/treedrawio-3.png)

```
Input: root = [1,2,null,3], k = 1
Output: 3
Explanation: The largest level sum is 3.
```

### Constraints

* The number of nodes in the tree is `n`.
* `2 <= n <= 10^5`
* `1 <= Node.val <= 10^6`
* `1 <= k <= n`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/kth_largest_sum_in_a_binary_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/kth_largest_sum_in_a_binary_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque

from leetcode_py import TreeNode


class Solution:
    # Time: O(n)
    # Space: O(w)
    def kth_largest_level_sum(self, root: TreeNode[int] | None, k: int) -> int:
        sums: list[int] = []
        queue = deque([root] if root is not None else [])
        while queue:
            level_sum = 0
            for _ in range(len(queue)):
                node = queue.popleft()
                level_sum += node.val
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)
            sums.append(level_sum)
        if k > len(sums):
            return -1
        sums.sort(reverse=True)
        return sums[k - 1]
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(w) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.