-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1448. Count Good Nodes in Binary Tree.cpp
More file actions
65 lines (45 loc) · 1.34 KB
/
Copy path1448. Count Good Nodes in Binary Tree.cpp
File metadata and controls
65 lines (45 loc) · 1.34 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<vector>
#include<iostream>
using namespace std;
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 {
public:
void depthFirstTraversal(TreeNode* node, int maxValue){
if(node->val >= maxValue){
goodNodeCount++;
}
maxValue = max(maxValue,node->val);
if(node->left){
depthFirstTraversal(node->left,maxValue);
}
if(node->right){
depthFirstTraversal(node->right,maxValue);
}
}
int goodNodes(TreeNode* root) {
depthFirstTraversal(root,-100000);
return goodNodeCount;
}
private:
int goodNodeCount = 0;
};
int main(){
Solution solution;
TreeNode* root = new TreeNode(-1);
TreeNode* n1 = new TreeNode(1);
root->left = n1;
n1->left = new TreeNode(3);
TreeNode* n2 = new TreeNode(4);
root->right = n2;
n2->left = new TreeNode(1);
n2->right = new TreeNode(5);
int answer = solution.goodNodes(root);
cout << "Answer is: " << answer << endl;
}