中等
这题在引用值传递的时候要注意maxdep前面的&,否则maxdep在如下的写法中输出答案会存在问题
/**
* 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 deepestLeavesSum(TreeNode* root) {
int s=0;
int maxdep=-1;
helper(root,1,maxdep,s);
return s;
}
void helper(TreeNode* p,int dep,int &maxdep,int &s){
if(p->left)
helper(p->left,dep+1,maxdep,s);
if(p->right)
helper(p->right,dep+1,maxdep,s);
if(!p->left&&!p->right)
if(dep>maxdep){
maxdep=dep;
s=p->val;
}
else if(dep==maxdep)
s+=p->val;
}
};