https://leetcode.com/problems/count-good-nodes-in-binary-tree/description/
This question is quick straightforward: top-down recursion.
And we need to pass down the maximum value so far during recursion.
Please see the code below:
/**
* 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) {
return !root ? 0 : dfs(root, root->val);
}
private:
int dfs(TreeNode* r, int val) {
return !r ? 0 : (r->val >= val ? 1 : 0) + dfs(r->left, max(r->val, val)) + dfs(r->right, max(r->val,val));
}
};
No comments:
Post a Comment