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

目录

  • Leetcode738.单调递增的数字
  • Leetcode968.监控二叉树

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

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

你可能感兴趣的:(算法)