和剑指offer里和为K的相似,这儿使用了霍纳法则来做的,很方便。
/**
* 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 sum,res;
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!root) return 0;
res=sum=0;
dfs(root);
return res;
}
void dfs(TreeNode *root){
if(!root) return;
sum=sum*10+root->val;
if(!root->left&&!root->right)
res+=sum;//这儿不能return
if(root->left!=NULL)
dfs(root->left);
if(root->right!=NULL)
dfs(root->right);
sum=(sum-root->val)/10;//回溯
}
};