problems(cpp): add „1448. Count Good Nodes in Binary Tree“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
f7ebb9037d
commit
dd94963a2f
1 changed files with 28 additions and 0 deletions
28
problems/count-good-nodes-in-binary-tree.cpp
Normal file
28
problems/count-good-nodes-in-binary-tree.cpp
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
/**
|
||||||
|
* Definition for a binary tree node.
|
||||||
|
* 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 {
|
||||||
|
int goodNodes(TreeNode* root, int m)
|
||||||
|
{
|
||||||
|
if (root == nullptr) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int new_max = std::max(m, root->val);
|
||||||
|
return (root->val >= m) + goodNodes(root->left, new_max) + goodNodes(root->right, new_max);
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
int goodNodes(TreeNode* root)
|
||||||
|
{
|
||||||
|
return goodNodes(root, INT_MIN);
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue