网址:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/
递归调用求和,同时注意%1000000007的位置
/** * 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: int getNum(TreeNode* t, int sum) { if(sum >= 1000000007) sum %= 1000000007; if(t->left == NULL && t->right == NULL) { return sum*2+t->val; } if(t->right && t->left) return getNum(t->left, sum*2+t->val)%1000000007+getNum(t->right, sum*2+t->val)%1000000007; else if(t->left) return getNum(t->left, sum*2+t->val); else return getNum(t->right, sum*2+t->val); } int sumRootToLeaf(TreeNode* root) { int ans = 0; ans = getNum(root, ans); return ans%1000000007; } };