c++
class Solution {
public:
void getMax(TreeNode *root, int deep, int &max_k, int &ans) {
if (!root) return ;
if (deep == max_k) ans += root->val;
if (deep > max_k) {
max_k = deep;
ans = root->val;
}
getMax(root->left, deep + 1, max_k, ans);
getMax(root->right, deep + 1, max_k, ans);
return ;
}
int deepestLeavesSum(TreeNode* root) {
int max_k = 0, ans = 0;
getMax(root, 0, max_k, ans);
return ans;
}
};
js
var deepestLeavesSum = function(root) {
var max_k = 0, ans = 0;
function getMax(root, k) {
if (!root) return ;
if (k == max_k) ans += root.val;
if (k > max_k) {
max_k = k;
ans = root.val;
}
getMax(root.left, k + 1);
getMax(root.right, k + 1);
return ;
}
getMax(root, 0);
return ans;
};