2792. Count Nodes That Are Great Enough
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
.
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
|
class Solution { priority_queue<int> dfs(TreeNode* node, int k, int& res) { priority_queue<int> self; if(node->left) { auto le = dfs(node->left,k,res); while(le.size()) { self.push(le.top()); le.pop(); } } if(node->right) { auto ri = dfs(node->right,k,res); while(ri.size()) { self.push(ri.top()); ri.pop(); } } while(self.size() > k) self.pop(); if(self.size() == k and self.top() < node->val) res += 1; self.push(node->val); return self; } public: int countGreatEnoughNodes(TreeNode* root, int k) { int res = 0; dfs(root,k,res); return res; } };
|