递归
- 思路:
- 递归子问题:
- sum = 左子树值 + 右子树值
- 子树值 = 上一级值 * 10 + 当前节点值
- 终止条件:
- 如果节点为 nullptr,则值为 0 ;
- 如果左子节点且右子节点为 nullptr,则返回数字和;
/**
* 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);
}
}
};