LeetCode 1022. 【递归】从根到叶的二进数之和
原题链接
简单
作者:
大明湖的鱼
,
2021-01-21 00:00:55
,
所有人可见
,
阅读 312
思路
- 把root的值*2加到左右孩子节点上
- 1e9+7 会被当成浮点数,要完整写出来,不知道为什么
/**
* 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 sumRootToLeaf(TreeNode* root) {
if(root == nullptr) return 0;
int mod = root->val % (1000000007);
if(root->left == nullptr && root->right == nullptr) return mod;
if(root->left != nullptr) root->left->val += mod << 1;
if(root->right != nullptr) root->right->val += mod << 1;
return (sumRootToLeaf(root->left) + sumRootToLeaf(root->right)) % (1000000007);
}
};