输入:root = [1,2,3] 输出:25 解释: 从根到叶子节点路径1->2
代表数字12
从根到叶子节点路径1->3
代表数字13
因此,数字总和 = 12 + 13 =25
输入:root = [1,0,1,0,1,0,1] 输出:22 解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
129. 求根节点到叶节点数字之和https://leetcode.cn/problems/sum-root-to-leaf-numbers/
/**
* 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 sumNumbers(TreeNode* root) {
return getNum(root,0);
}
int getNum(TreeNode* root,int num) {
if(root==nullptr) {
return 0;
}
num = num*10+root->val;
if(root->left==nullptr&&root->right==nullptr) {
return num;
}
return getNum(root->left,num)+getNum(root->right,num);
}
};
1022. 从根到叶的二进制数之和https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
return getNum(root,0);
}
int getNum(TreeNode* root,int num) {
if(root==nullptr) {
return 0;
}
num = num*2+root->val;
if(root->left==nullptr&&root->right==nullptr) {
return num;
}
return getNum(root->left,num)+getNum(root->right,num);
}
};
两个题目本质上是一道内容:
唯一的修改点是:
num = num*2+root->val;
num = num*10+root->val;