-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_1448_CountGoodNodesInBT.cpp
66 lines (57 loc) · 1.52 KB
/
LC_1448_CountGoodNodesInBT.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
https://leetcode.com/problems/count-good-nodes-in-binary-tree/
1448. Count Good Nodes in Binary Tree
*/
/**
* 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 {
public:
void myprint(vector<int> vec) { for(int x: vec) cout<<x<<" "; cout<<endl; }
int cnt=0;
int goodNodes(TreeNode* root) {
countGN(root, INT_MIN);
return cnt;
}
void countGN(TreeNode* root, int mxval)
{
if(!root)
return;
if(!root->left and !root->right)
{
if(root->val >= mxval)
cnt++;
return;
}
if(root->val >= mxval)
{
cnt++;
mxval = root->val;
}
countGN(root->left, mxval);
countGN(root->right, mxval);
}
int count(TreeNode* root, int mxval)
{
if(!root)
return 0;
if(!root->left and !root->right)
return (root->val >= mxval);
int val = 0;
if(root->val >= mxval)
{
val = 1;
mxval = root->val;
}
// myprint({root->val, mxval, val});
return val + count(root->left, mxval) + count(root->right, mxval);
}
};