Leetcode #2583: Kth Largest Sum in a Binary Tree
In this guide, we solve Leetcode #2583 Kth Largest Sum in a Binary Tree in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Tree, Breadth-First Search, Binary Tree, Sorting
Intuition
We need level-by-level exploration or shortest steps, which is ideal for BFS.
A queue naturally models the frontier of the search.
Approach
Push initial nodes into a queue and expand in layers.
Track visited nodes to prevent cycles.
Steps:
- Initialize queue with start nodes.
- Process level by level.
- Track visited nodes.
Example
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.
Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
arr = []
q = deque([root])
while q:
t = 0
for _ in range(len(q)):
root = q.popleft()
t += root.val
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
arr.append(t)
return -1 if len(arr) < k else nlargest(k, arr)[-1]
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.