-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2792-count-nodes-that-are-great-enough.js
More file actions
51 lines (44 loc) · 1.31 KB
/
2792-count-nodes-that-are-great-enough.js
File metadata and controls
51 lines (44 loc) · 1.31 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
51
/**
* 2792. Count Nodes That Are Great Enough
* https://leetcode.com/problems/count-nodes-that-are-great-enough/
* Difficulty: Hard
*
* You are given a root to a binary tree and an integer k. A node of this tree is called great
* enough if the followings hold:
* - Its subtree has at least k nodes.
* - Its value is greater than the value of at least k nodes in its subtree.
*
* Return the number of nodes in this tree that are great enough.
*
* The node u is in the subtree of the node v, if u == v or v is an ancestor of u.
*/
/**
* 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 countGreatEnoughNodes = function(root, k) {
let result = 0;
dfs(root);
return result;
function dfs(node) {
if (!node) return [];
const leftValues = dfs(node.left);
const rightValues = dfs(node.right);
const combined = [...leftValues, ...rightValues].sort((a, b) => a - b).slice(0, k);
if (combined.length >= k && combined[k - 1] < node.val) {
result++;
} else {
combined.push(node.val);
}
return combined;
}
};