---
# System prepended metadata

title: 2583. Kth Largest Sum in a Binary Tree
tags: [Leetcode, Level Order Traversal, Tree, Medium]

---

# 2583. Kth Largest Sum in a Binary Tree
###### tags: `Leetcode` `Medium` `Tree` `Level Order Traversal`
Link: https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/description/
## Code
```java=
class Solution {
    public long kthLargestLevelSum(TreeNode root, int k) {
        Queue<Long> pq = new PriorityQueue<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()){
            int size = q.size();
            long sum = 0;
            for(int i=0; i<size; i++){
                TreeNode curr = q.poll();
                sum += curr.val;
                if(curr.left!=null) q.add(curr.left);
                if(curr.right!=null) q.add(curr.right);
            }
            pq.add(sum);
            if(pq.size()>k) pq.poll();
        }
        if(pq.size()<k) return -1;
        else return pq.peek();
    }
}
```