Kth Largest Sum in a Binary Tree — LeetCode 2583 Python Solution

MediumTreeBreadth-First SearchBinary TreeSorting
Problem
#2583
Reading time
4 min

The 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.

Example

Input
root = [5,8,9,2,1,3,7,4,6], k = 2
Output
13
Explanation
The level sums are the following:

Python solution

Python
# 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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2583. Kth Largest Sum in a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2583. Kth Largest Sum in a Binary Tree?
LeetCode 2583. Kth Largest Sum in a Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 2583. Kth Largest Sum in a Binary Tree?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2583. Kth Largest Sum in a Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2583. Kth Largest Sum in a Binary Tree cover?
LeetCode 2583. Kth Largest Sum in a Binary Tree is tagged Tree, Breadth-First Search, Binary Tree and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview