举例:如下图,124+125+136 = 386
int sumTree(TreeNode* node,int sum)
{
if(node==nullptr)
{
return 0;
}
if(node->left==nullptr && node->right==nullptr)
{
sum*=10;
sum+=node->val;
return sum;
}
sum *=10;
sum += node->val;
int sum_left = sumTree(node->left,sum);
int sum_right = sumTree(node->right,sum);
return sum_left+sum_right;
}
int sum(TreeNode* root) {
return sumTree(root,0);
}