还是dfs。跟Minimum Depth of Binary Tree以及Maximum Depth of Binary Tree很像。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
sum = 0;
if(!root) return sum;
dfs(root, 0);
return sum;
}
void dfs(TreeNode *root, int n){
if(!root) return ;
if(!root->left && !root->right){
sum += (n*10 + root->val);
return ;
}
dfs(root->left, n*10+root->val);
dfs(root->right, n*10+root->val);
}
int sum;
};