题目链接https://leetcode.cn/problems/kth-largest-sum-in-a-binary-tree/?envType=daily-question&envId=2024-02-23
和我上一篇发的博客类似,通过广度优先遍历二叉树,使用队列存每层的节点值,
最后再做处理,输出第K大层和
class Solution {public long kthLargestLevelSum(TreeNode root, int k) {List<Long> res = new ArrayList<>();Queue<TreeNode> queue = new ArrayDeque<>();if (root != null) {queue.add(root);}while (!queue.isEmpty()) {int n = queue.size();List<Integer> level = new ArrayList<>();long levelSum = 0;for (int i = 0; i < n; i++) { TreeNode node = queue.poll();levelSum += node.val;level.add(node.val);if (node.left != null) {queue.add(node.left);}if (node.right != null) {queue.add(node.right);}}res.add(levelSum);}if(res.size() < k){return -1;}Collections.sort(res);return res.get(res.size() - k);}
}