#2583
Medium Algorithms Kth largest sum in a binary tree
Tree Breadth-First Search Sorting Binary Tree
59.0% acceptance
Feb 25, 2026
1072
40
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.
Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1.
Note that two nodes are on the same level if they have the same distance from the root.
Solution
Rust
Time O(n²)
Space O(n)
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn kth_largest_level_sum(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i64 {
use std::collections::VecDeque;
let mut level_sums = Vec::new();
let mut queue = VecDeque::new();
if let Some(r) = root { queue.push_back(r); }
while !queue.is_empty() {
let level_size = queue.len();
let mut sum = 0i64;
for _ in 0..level_size {
let node = queue.pop_front().unwrap();
let n = node.borrow();
sum += n.val as i64;
if let Some(l) = n.left.clone() { queue.push_back(l); }
if let Some(r) = n.right.clone() { queue.push_back(r); }
}
level_sums.push(sum);
}
let k = k as usize;
if k > level_sums.len() { return -1; }
level_sums.sort_unstable_by(|a, b| b.cmp(a));
level_sums[k - 1]
}
}