#2583

Kth Largest Sum in a Binary Tree

specialist · 730 · lc medium +31 · verified · 59% accepted · 1,074 likes · top 56%

Description

Given the root of a binary tree and a positive integer k, compute the sum of node values at each level (depth). Return the k-th largest level sum, or -1 if the tree has fewer than k levels.

Example 1:

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:

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

Code

1
2
3
4
5
6
7
8
9