Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

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.

Leetcode

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 O(n×log⁡n)O(n \times \log n)O(n×logn), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

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.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy