Count Good Nodes in Binary Tree LeetCode solution in C++

1
class Solution {
2
public:
3
int count = 0;
4
void sol(TreeNode *root, int gr) {
5
if (!root) return; // base condition
6

7
if (gr <= root->val) { // check point max element increase count
8
gr = max(gr, root->val);
9
count++;
10
}
11

12
if (root->left) sol(root->left, gr);
13
if (root->right) sol(root->right, gr);
14
}
15
int goodNodes(TreeNode *root) {
16
if (!root->left && !root->right) return 1; // check for if there is one node
17
int gr = root->val;
18
sol(root, gr);
19
return count;
20
}
21
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0