算法训练营第三十七天|738.单调递增的数字 968.监控二叉树

2024-01-07 18:04:12

Leetcode738.单调递增的数字

文章链接:代码随想录
题目链接:738.单调递增的数字

把数字转换成字符串操作更方便

class Solution {
public:
    int monotoneIncreasingDigits(int n) {
        string num = to_string(n);
        int flag = INT_MAX;
        for (int i = num.size() - 1; i > 0; i--){
            if (num[i - 1] > num[i]) {
                num[i - 1]--;
                flag = i;
            }
        }
        for (int i = flag; i < num.size(); i++){
            num[i] = '9';
        }
        return stoi(num);
    }
};

Leetcode968.监控二叉树

文章链接:代码随想录
题目链接:968.监控二叉树

/**
 * 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 traversal(TreeNode* cur, int& result){
        if (cur == NULL) return 2;
        int l = traversal(cur->left, result);
        int r = traversal(cur->right, result);
        if (l == 2 && r == 2) return 0;

        if (l == 0 || r == 0) {
            result++;
            return 1;
        }

        if (l == 1 || r == 1) return 2;
        
        return -1;
    }
    
    int minCameraCover(TreeNode* root) {
        int result = 0;
        if (traversal(root, result) == 0) result++;
        return result;
    }
};

第三十七天打卡,加油!!!

文章来源:https://blog.csdn.net/qq_55232233/article/details/135381950
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。