力扣1022 從根到葉的二叉樹之和 遞歸

1、

2、

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    const long num=1e9+7;//放置溢出用的
    int sumRootToLeaf(TreeNode* root) {
        long p=0;
        long res=0;
        dfs(root,p,res);
        return res;
    }
    void dfs(TreeNode* root,long p,long& res)
    {
        if(root==nullptr) return;
        p=p<<1|(root->val);
        if(root->left==nullptr&&root->right==nullptr)
        {
            res+=p;
            res%=num;
        }
        dfs(root->left,p,res);
        dfs(root->right,p,res);
    }
};










 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章