程式語言 - 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;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int travel(struct TreeNode *n, int m, int *cnt)
{
    if (!n) {
        return 0;
    }

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

    return travel(n->left, m, cnt) + travel(n->right, m, cnt);
}

int goodNodes(struct TreeNode* root)
{
    int m = 0;
    int cnt = 0;

    if (!root) {
        return 0;
    }

    m = INT_MIN;
    travel(root, m, &cnt);

    return cnt;
}