Ctrl K

K-th Heaviest Tree Level

Medium
You get the root of a binary tree and a positive integer rank. The *weight* of a level is the sum of the values of all nodes at the same distance from the root. Sort the weights of all levels from largest to smallest and return the one in position rank (counting from 1). Equal weights take separate positions. If the tree has fewer than rank levels, return -1.
Example 1
root=tree_node([4, 7, 2, 1, None, 9, 3]), rank=2 → 9

The level totals are 4, then 7 + 2 = 9, then 1 + 9 + 3 = 13. Sorted from largest: 13, 9, 4, so second place goes to 9.

Example 2
root=tree_node([6, 3, 3, None, 6]), rank=1 → 6

All three levels total 6, so first place is 6. Equal totals still count as separate places.

Example 3
root=tree_node([2, 5, 1]), rank=3 → -1

There are three nodes but only two levels (2 and 5 + 1 = 6), so there is no third place: the answer is -1.

Constraints
  • The tree has between 2 and 10⁵ nodes
  • 1 ≤ Node.val ≤ 10⁶
  • 1 ≤ rank ≤ number of nodes
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Columns, Top Down MediumTree Columns With Ties HardTree Rows by Depth MediumSnake Through the Tree Levels MediumTree Levels From the Bottom Up Medium
loading Python…
Input
root=tree_node([4, 7, 2, 1, None, 9, 3]), rank=2
Expected
9

Run checks the first 3 tests in your browser. Submit checks all 46 tests on the server, hidden ones included.