Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
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.
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.
Constraints:
n.2 <= n <= 1051 <= Node.val <= 1061 <= k <= nProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[5,8,9,2,1,3,7,4,6] 2
[1,2,null,3] 1
binary-tree-preorder-traversal)maximum-level-sum-of-a-binary-tree)find-the-level-of-tree-with-minimum-sum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2583: Kth Largest Sum in a Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public long kthLargestLevelSum(TreeNode root, int k) {
List<Long> arr = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
long t = 0;
for (int n = q.size(); n > 0; --n) {
root = q.pollFirst();
t += root.val;
if (root.left != null) {
q.offer(root.left);
}
if (root.right != null) {
q.offer(root.right);
}
}
arr.add(t);
}
if (arr.size() < k) {
return -1;
}
Collections.sort(arr, Collections.reverseOrder());
return arr.get(k - 1);
}
}
// Accepted solution for LeetCode #2583: Kth Largest Sum in a Binary Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthLargestLevelSum(root *TreeNode, k int) int64 {
arr := []int{}
q := []*TreeNode{root}
for len(q) > 0 {
t := 0
for n := len(q); n > 0; n-- {
root = q[0]
q = q[1:]
t += root.Val
if root.Left != nil {
q = append(q, root.Left)
}
if root.Right != nil {
q = append(q, root.Right)
}
}
arr = append(arr, t)
}
if n := len(arr); n >= k {
sort.Ints(arr)
return int64(arr[n-k])
}
return -1
}
# Accepted solution for LeetCode #2583: Kth Largest Sum in a Binary Tree
# 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]
// Accepted solution for LeetCode #2583: Kth Largest Sum in a Binary Tree
/**
* [2583] Kth Largest Sum in a Binary Tree
*/
pub struct Solution {}
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn kth_largest_level_sum(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i64 {
let root = if let Some(r) = root {
r
} else {
return -1;
};
let k = k as usize;
let mut levels = Vec::new();
let mut level = vec![root];
while !level.is_empty() {
let mut new_level = Vec::new();
let mut sum = 0;
for node in level {
sum += node.borrow().val as i64;
if let Some(left) = &node.borrow().left {
new_level.push(Rc::clone(left));
}
if let Some(right) = &node.borrow().right {
new_level.push(Rc::clone(right));
}
}
levels.push(sum);
level = new_level;
}
if levels.len() < k {
return -1;
}
levels.sort_unstable();
levels[levels.len() - k]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2583() {}
}
// Accepted solution for LeetCode #2583: Kth Largest Sum in a Binary Tree
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function kthLargestLevelSum(root: TreeNode | null, k: number): number {
const arr: number[] = [];
const q = [root];
while (q.length) {
let t = 0;
for (let n = q.length; n > 0; --n) {
root = q.shift();
t += root.val;
if (root.left) {
q.push(root.left);
}
if (root.right) {
q.push(root.right);
}
}
arr.push(t);
}
if (arr.length < k) {
return -1;
}
arr.sort((a, b) => b - a);
return arr[k - 1];
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.