int sum = prevSum * 10 + root->val;
calcSum(root->left, sum) + calcSum(root->right, sum);
/**
* 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 calcSum(root, 0);
}
private:
int calcSum(TreeNode* root, int prevSum) {
if (root == nullptr) {
return 0;
}
int sum = prevSum * 10 + root->val;
if (root->left == nullptr && root->right == nullptr) {
return sum;
} else {
return calcSum(root->left, sum) + calcSum(root->right, sum);
}
}
};
更多【算法-力扣129. 求根节点到叶节点数字之和】相关视频教程:www.yxfzedu.com