题目:
Given a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15
Constraints:
- The number of nodes in the tree is between
1
and10^4
. - The value of nodes is between
1
and100
.
代码:
/**
* 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:
map<int, int> m;
void helper(TreeNode* root,int level,int& maxl) {
if (!root)return;
m[level] += root->val;
maxl = max(maxl, level);
helper(root->left, level + 1,maxl);
helper(root->right, level + 1,maxl);
}
int deepestLeavesSum(TreeNode* root) {
if (!root)return 0;
int maxl = 0;
helper(root, 0, maxl);
return m[maxl];
}
};