Count Good Nodes in Binary Tree SOLUTION

Count Good Nodes in Binary Tree SOLUTION

This question is quick straightforward: top-down recursion. And we need to pass down the maximum value so far during recursion.

SOLUTION

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));
    }
};

Leave a Comment

eighteen − five =