-
Notifications
You must be signed in to change notification settings - Fork 6
/
1448.cpp
48 lines (38 loc) · 928 Bytes
/
1448.cpp
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
41
42
43
44
45
46
47
48
// Solution 1 :-
class Solution {
private:
int m_sum = 0;
public:
void countGood(TreeNode *root, int max = INT_MIN) {
if (!root)
return;
if (max <= root->val)
m_sum++;
max = std::max(root->val, max);
countGood(root->right, max);
countGood(root->left, max);
}
int goodNodes(TreeNode *root) {
countGood(root);
return m_sum;
}
};
// Solution 2 :-
class Solution {
public:
int traverse(TreeNode* root, int maxVal) {
if (!root)
return 0;
int goodNode = 0;
if (root -> val >= maxVal) {
goodNode++;
maxVal = root -> val;
}
return goodNode + traverse(root -> left, maxVal) + traverse(root -> right, maxVal);
}
int goodNodes(TreeNode* root) {
if (!root)
return 0;
return traverse(root, root -> val);
}
};