Count Nodes That Are Great Enough — LeetCode 2792 Python Solution

HardLeetCode PremiumTreeDepth-First SearchDivide and ConquerBinary Tree
Problem
#2792
Reading time
5 min

The problem

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.

Example

Input
root = [7,6,5,4,3,2,1], k = 2
Output
3
Explanation
Number the nodes from 1 to 7.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countGreatEnoughNodes(self, root: Optional[TreeNode], k: int) -> int:
        def push(pq, x):
            heappush(pq, x)
            if len(pq) > k:
                heappop(pq)

        def dfs(root):
            if root is None:
                return []
            l, r = dfs(root.left), dfs(root.right)
            for x in r:
                push(l, x)
            if len(l) == k and -l[0] < root.val:
                nonlocal ans
                ans += 1
            push(l, -root.val)
            return l

        ans = 0
        dfs(root)
        return ans

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2792. Count Nodes That Are Great Enough is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2792. Count Nodes That Are Great Enough?
LeetCode 2792. Count Nodes That Are Great Enough is rated Hard on LeetCode.
What is the time complexity of LeetCode 2792. Count Nodes That Are Great Enough?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 2792. Count Nodes That Are Great Enough?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 2792. Count Nodes That Are Great Enough cover?
LeetCode 2792. Count Nodes That Are Great Enough is tagged Tree, Depth-First Search, Divide and Conquer and Binary Tree on LeetCode.
Is LeetCode 2792. Count Nodes That Are Great Enough a premium problem?
Yes. LeetCode 2792. Count Nodes That Are Great Enough is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview