[LeetCode 257,258][简单]二叉树的所有路径/各位相加

257.二叉树的所有路径
题目链接

class Solution {
public:
    vector<string>ans;
    string path="";
    void getans(TreeNode* root,string path){
        if(root)path += to_string(root->val);
        else return ;
        if(!(root->left||root->right))ans.emplace_back(path);
        else path += "->";
        getans(root->left,path);
        getans(root->right,path);
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        ios::sync_with_stdio(0);
        getans(root,path);
        return ans;
    }
};

258.各位相加
题目链接
简单证明一下:
1. a [ 0 ] 1 0 0 + a [ 1 ] 1 0 1 + . . . + a [ n ] 1 0 n i = 0 n a [ i ] 1.a[0]*10^0 + a[1]*10^1+...+a[n]*10^n \rightarrow \sum_{i=0}^{n}{a[i]}
2. Δ = i = 1 n ( 1 0 i 1 ) a [ i ] 2.左减右\Delta=\sum_{i=1}^{n}{(10^i-1)a[i]}
3. : Δ % 9 = = 0 Δ > 0   i f   i > 0 Δ < l e f t 3.显然: \\ \Delta \%9==0\\ \Delta > 0\ if\ i>0\\ \Delta <left
4. 3 10 10 0 9 4.由3得一个大于10的数一定会收敛到一个小于10大于0的值,并且每次的减量是9的倍数
5. n u m 9 9 n u m % 9 5.如果num是9的倍数,答案是9,否则答案为num\%9

class Solution {
public:
    int addDigits(int num) {
        return (num-1)%9+1;
    }
};
发布了104 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/IDrandom/article/details/104379273