Count Nodes That Are Great Enough - Problem
Count Nodes That Are Great Enough
You are given the
A node is considered great enough if it satisfies both of these conditions:
1. Size condition: Its subtree contains at least
2. Value condition: Its value is greater than the values of at least
Note that a node is considered to be in its own subtree. A subtree of node
Goal: Return the total count of nodes that meet both criteria.
Example: If
You are given the
root of a binary tree and an integer k. Your task is to identify and count all the "great enough" nodes in the tree.A node is considered great enough if it satisfies both of these conditions:
1. Size condition: Its subtree contains at least
k nodes (including itself)2. Value condition: Its value is greater than the values of at least
k nodes in its subtreeNote that a node is considered to be in its own subtree. A subtree of node
v includes v itself and all nodes that have v as an ancestor.Goal: Return the total count of nodes that meet both criteria.
Example: If
k = 2, a node needs to have at least 2 nodes in its subtree AND its value must be greater than at least 2 values in that subtree. Input & Output
example_1.py — Basic Tree
$
Input:
root = [5,3,7,1,4,null,null], k = 2
›
Output:
1
💡 Note:
Node 5 has subtree [5,3,7,1,4] with size 5 ≥ 2 and values [1,3,4] are smaller than 5, so 3 ≥ 2. Node 3 has subtree [3,1,4] with size 3 ≥ 2 but only 1 value is smaller than 3, so 1 < 2. Other nodes have subtree size < 2. Only node 5 qualifies.
example_2.py — Single Node
$
Input:
root = [10], k = 1
›
Output:
0
💡 Note:
Single node with value 10. Subtree has 1 node ≥ 1, but there are 0 nodes smaller than 10 in its subtree, and 0 < 1, so it doesn't qualify.
example_3.py — Large k
$
Input:
root = [1,2,3], k = 5
›
Output:
0
💡 Note:
No node has a subtree with at least 5 nodes, so no nodes can be great enough regardless of value conditions.
Constraints
- 1 ≤ number of nodes ≤ 104
- 1 ≤ Node.val ≤ 104
- 1 ≤ k ≤ 104
- All node values are unique
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code