Skip to content

2792. Count Nodes That Are Great Enough 👍

  • Time: $O(n)$
  • Space: $O(h)$
 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
class Solution {
 public:
  int countGreatEnoughNodes(TreeNode* root, int k) {
    int ans = 0;
    dfs(root, k, ans);
    return ans;
  }

 private:
  multiset<int> dfs(TreeNode* root, int k, int& ans) {
    if (root == nullptr)
      return {};

    multiset<int> kSmallest = dfs(root->left, k, ans);
    multiset<int> kSmallestRight = dfs(root->right, k, ans);
    kSmallest.merge(kSmallestRight);

    if (kSmallest.size() > k)
      kSmallest.erase(next(kSmallest.begin(), k), kSmallest.end());
    if (kSmallest.size() == k && root->val > *kSmallest.rbegin())
      ++ans;

    kSmallest.insert(root->val);
    return kSmallest;
  }
};
 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
class Solution {
  public int countGreatEnoughNodes(TreeNode root, int k) {
    dfs(root, k);
    return ans;
  }

  private int ans = 0;

  private Queue<Integer> dfs(TreeNode root, int k) {
    if (root == null)
      return new PriorityQueue<>(Collections.reverseOrder());

    Queue<Integer> kSmallest = dfs(root.left, k);
    Queue<Integer> kSmallestRight = dfs(root.right, k);
    kSmallest.addAll(kSmallestRight);

    while (kSmallest.size() > k)
      kSmallest.poll();
    if (kSmallest.size() == k && root.val > kSmallest.peek())
      ++ans;

    kSmallest.offer(root.val);
    return kSmallest;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def countGreatEnoughNodes(self, root: TreeNode | None, k: int) -> int:
    ans = 0

    def dfs(root: TreeNode | None) -> list[int]:
      nonlocal ans
      if not root:
        return []

      kSmallest = sorted(dfs(root.left) + dfs(root.right))[:k]
      if len(kSmallest) == k and root.val > kSmallest[-1]:
        ans += 1

      return kSmallest + [root.val]

    dfs(root)
    return ans