LeetCode 1448. 统计二叉树中好节点的数目

手写思路

这题中等难度,正确率好像70%+
在这里插入图片描述

代码

Talk is cheap, show me the code.

/**
 * 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 count = 0;
    int goodNodes(TreeNode* root) {
    
    
        if(root){
    
    
            good(root, root->val); // 注意root->val的值可能是负数, 这里不能一开始Maximum就为0
        }
        return count;
    }

    void good(TreeNode* root, int Maximum){
    
    
        if(root){
    
    
        	// 1. 判断root是不是好节点
            if(root->val >= Maximum){
    
    
                count++;
                Maximum = root->val;
                // cout << Maximum << endl;
            }
            // 2. 判断左子树和右子树中各有几个好节点
            good(root->left, Maximum);
            good(root->right, Maximum);
        }
    }

};

猜你喜欢

转载自blog.csdn.net/skywuuu/article/details/115342053