Any neater solution for processing variable during recursion?

• ``````/**
* 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;
}
vector<int> nums;
string tmp;
//tmp = to_string(root->val);
//dfs(root->left, nums, tmp);
//tmp = to_string(root->val);
//dfs(root->right, nums, tmp);
dfs(root, nums, tmp);
int ret=0;
for(int i=0; i<nums.size(); i++)
{
ret+=nums[i];
}
return ret;
}
void dfs(TreeNode* root, vector<int>& nums, string& tmp)
{
if(!root->left && !root->right)
{
tmp+=to_string(root->val);
int num = stoi(tmp);
nums.push_back(num);
tmp.erase(tmp.size()-1,1);
return;
}
else if(!root->right && root->left)
{
tmp+=to_string(root->val);
dfs(root->left, nums, tmp);
tmp.erase(tmp.size()-1,1);
}
else if(!root->left && root->right)
{
tmp+=to_string(root->val);
dfs(root->right, nums, tmp);
tmp.erase(tmp.size()-1,1);
}
else
{
tmp+=to_string(root->val);
dfs(root->left, nums, tmp);
tmp.erase(tmp.size()-1,1);
tmp+=to_string(root->val);
dfs(root->right, nums, tmp);
tmp.erase(tmp.size()-1,1);
}
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.