LeetCode 129. Sum Root to Leaf Numbers
Solution1:我的答案
二叉树路径和问题,类似113
/**
* 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 sumNumbers(TreeNode* root) {
if (!root) return 0;
int sum = 0;
vector<int> temp;
my_sum(root, temp, sum);
return sum;
}
void my_sum(TreeNode* root, vector<int>& temp, int &sum) {
if (!root) return;
temp.push_back(root->val);
if (!root->left && !root->right) {
int temp_sum = 0;
for (int i = 0; i < temp.size(); i++)
temp_sum = temp_sum * 10 + temp[i];
sum += temp_sum;
}
my_sum(root->left, temp, sum);
my_sum(root->right, temp, sum);
temp.pop_back();
}
};