Skip to content

Commit ccd8b99

Browse files
committed
6308. 二叉树中的第 K 大层和
1 parent 9029bb8 commit ccd8b99

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@
243243
|2341|[数组能形成多少数对](https://leetcode.cn/problems/maximum-number-of-pairs-in-array/)|[JavaScript](./algorithms/maximum-number-of-pairs-in-array.js)|Easy|
244244
|2351|[第一个出现两次的字母](https://leetcode.cn/problems/first-letter-to-appear-twice/)|[JavaScript](./algorithms/first-letter-to-appear-twice.js)|Easy|
245245
|2357|[使数组中所有元素都等于零](https://leetcode.cn/problems/make-array-zero-by-subtracting-equal-amounts/)|[JavaScript](./algorithms/make-array-zero-by-subtracting-equal-amounts.js)|Easy|
246+
|6308|[二叉树中的第 K 大层和](https://leetcode.cn/problems/kth-largest-sum-in-a-binary-tree/)|[JavaScript](./algorithms/kth-largest-sum-in-a-binary-tree.js)|Medium|
246247
|6354|[找出数组的串联值](https://leetcode.cn/problems/find-the-array-concatenation-value/)|[JavaScript](./algorithms/find-the-array-concatenation-value.js)|Easy|
247248
|6362|[合并两个二维数组 - 求和法](https://leetcode.cn/problems/merge-two-2d-arrays-by-summing-values/)|[JavaScript](./algorithms/merge-two-2d-arrays-by-summing-values.js)|Easy|
248249
|6367|[求出最多标记下标](https://leetcode.cn/problems/find-the-maximum-number-of-marked-indices/)|[JavaScript](./algorithms/find-the-maximum-number-of-marked-indices.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* 6308. 二叉树中的第 K 大层和
11+
* @param {TreeNode} root
12+
* @param {number} k
13+
* @return {number}
14+
*/
15+
var kthLargestLevelSum = function (root, k) {
16+
// BFS
17+
let depth = 0;
18+
const queue = [root];
19+
let result = [];
20+
21+
while (queue.length) {
22+
let size = queue.length;
23+
let sum = 0;
24+
while (size--) {
25+
const node = queue.shift();
26+
sum += node.val;
27+
node.left && queue.push(node.left);
28+
node.right && queue.push(node.right);
29+
}
30+
result.push(sum);
31+
depth++;
32+
}
33+
if (k > depth) return -1;
34+
result.sort((a, b) => b - a);
35+
36+
return result[k - 1] ? result[k - 1] : -1;
37+
};

0 commit comments

Comments
 (0)