forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1448-Count-Good-Nodes-In-Binary-Tree.cpp
41 lines (36 loc) · 1.05 KB
/
1448-Count-Good-Nodes-In-Binary-Tree.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
/*
Given binary tree, node is "good" if path from root has no nodes > X, return # of "good"
Maintain greatest value seen so far on a path, if further node >= this max, "good" node
Time: O(n)
Space: O(n)
*/
/**
* 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:
int goodNodes(TreeNode* root) {
int result = 0;
dfs(root, root->val, result);
return result;
}
private:
void dfs(TreeNode* root, int maxSoFar, int& result) {
if (root == NULL) {
return;
}
if (root->val >= maxSoFar) {
result++;
}
dfs(root->left, max(maxSoFar, root->val), result);
dfs(root->right, max(maxSoFar, root->val), result);
}
};