给你一棵二叉树,请你返回层数最深的叶子节点的和。
示例:
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
提示:
- 树中节点数目在
1
到10^4
之间。 - 每个节点的值在
1
到100
之间。
C++
/**
* 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:
void dfs(TreeNode* root, map<int,vector<int>>& tmp, int k)
{
if(root)
{
tmp[k].push_back(root->val);
dfs(root->left,tmp,k+1);
dfs(root->right,tmp,k+1);
}
}
int deepestLeavesSum(TreeNode* root)
{
map<int,vector<int>> tmp;
dfs(root,tmp,1);
int n=0;
for(auto it:tmp)
{
if(it.first>n)
{
n=it.first;
}
}
vector<int> vec=tmp[n];
int res=accumulate(vec.begin(),vec.end(),0);
return res;
}
};