程式語言 - LeetCode - C++ - 1448. Count Good Nodes in Binary Tree



參考資訊:
https://www.cnblogs.com/cnoodle/p/14503186.html

題目:


解答:

/**
 * 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 dfs(TreeNode *n, int &r, int m) {
        if (!n) {
            return -1;
        }

        if (n->val >= m) {
            r += 1;
            m = n->val;
        }

        dfs(n->left, r, m);
        dfs(n->right, r, m);
        return 0;
    }

    int goodNodes(TreeNode* root) {
        int r = 0;

        if (!root) {
            return 0;
        }

        dfs(root, r, root->val);
        return r;
    }
};