Description
Submission
/**
* 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 {
int ret;
void dfs(TreeNode* cur, int val) {
if(!cur) return;
if(cur->left == nullptr && cur->right == nullptr) {
ret += val * 10 + cur->val;
return;
}
int newVal = val * 10 + cur->val;
dfs(cur->left, newVal);
dfs(cur->right, newVal);
}
public:
int sumNumbers(TreeNode* root) {
ret = 0;
dfs(root, 0);
return ret;
}
};