-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2583-kth-largest-sum-in-a-binary-tree.js
More file actions
50 lines (44 loc) · 1.32 KB
/
2583-kth-largest-sum-in-a-binary-tree.js
File metadata and controls
50 lines (44 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 2583. Kth Largest Sum in a Binary Tree
* https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/
* Difficulty: Medium
*
* 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.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthLargestLevelSum = function(root, k) {
const levelSums = [];
const queue = [root];
while (queue.length) {
let levelSize = queue.length;
let levelSum = 0;
while (levelSize--) {
const node = queue.shift();
levelSum += node.val;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
levelSums.push(levelSum);
}
if (levelSums.length < k) return -1;
return levelSums.sort((a, b) => b - a)[k - 1];
};