822. Count Nodes That Are Great Enough

You are provided with the root of a binary tree and an integer k. In this tree, a node is considered great enough if both of the following conditions are met:

  • The subtree rooted at that node (which includes the node itself) contains at least k nodes.
  • The node's value is greater than the values of at least k nodes within its subtree.

A node u is part of the subtree of node v if either u == v or v is an ancestor of u.

Your task is to determine and return the total number of nodes in the tree that are great enough.

Example 1:

Input : root = [7,6,5,4,3,2,1], k = 2

Output : 3

Explanation :

  • For the node with value 7:
  • Its subtree contains {1,2,3,4,5,6,7}. Since 7 is greater than 6 nodes in its subtree, it qualifies as great enough.
  • For the node with value 6:
  • Its subtree contains {3,4,6}. Since 6 is greater than exactly 2 nodes, it is great enough.
  • For the node with value 5:
  • Its subtree contains {1,2,5}. Since 5 is greater than exactly 2 nodes, it is great enough.
  • No other node meets both conditions.

Example 2:

Input : root = [1,2,3], k = 1

Output : 0

Explanation :

  • For every node in this tree, there is no instance where a node's value is greater than at least 1 other node in its subtree. Therefore, none of the nodes qualify as great enough.

Now Your Turn!

Pick the correct output for the given input

Input : root = [3,2,2], k = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [1, 10⁴].
  • 1 <= Node.val <= 10⁴
  • 1 <= k <= 10

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
// struct TreeNode
// {
// int val;
// TreeNode *left;
// TreeNode *right;
// TreeNode() : val(0), left(nullptr), right(nullptr) {}
// TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
// TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
// };
 
class Solution {
public:
int countGreatEnoughNodes(TreeNode *root, int k) {
// Your Code goes here
}
};
Test Case

Input:

K
Root