Code random record algorithm training camp day37 || 738. Monotonically increasing numbers 968. Monitoring binary tree

I learned a lot of basic knowledge of c++ today, but if you can find the rules in the array when doing the first question, it will be easy to do. The second question revisited the binary tree.

Problem 1: 738. Monotonically increasing numbers - LeetCode

Idea: When the previous number is greater than the next number, you need to change the previous number -1 and the last number to 9. On this basis, first convert the number to a string, then traverse it, record the position of the number that needs to be changed by 9, and adjust it after the traversal. The code is as follows:

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

Question 2: 968. Monitoring Binary Tree - LeetCode

Idea: The idea of ​​this question is difficult to think about. First, use numbers to represent the status of nodes, which is convenient for writing judgment statements. 0 means not covered, 1 means that the camera is installed, and 2 means covered. Then traverse the binary tree. It is easier to use post-order traversal for this question. The code is as follows:

class Solution {
public:
    int result=0;
    int traversal(TreeNode* cur){
        if(cur==nullptr) return 2;
        int left=traversal(cur->left);
        int right=traversal(cur->right);
        if(left == 0 || right == 0){
            result++;
            return 1;
        }
        if(left==2 && right==2) return 0;
        return 2;
    }
    int minCameraCover(TreeNode* root) {
        if(traversal(root)==0){
            result++;
        }
        return result;
    }
};

Guess you like

Origin blog.csdn.net/weixin_56969073/article/details/132349325