给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。

示例 1:

1302. 层数最深叶子节点的和_二叉树

输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15

示例 2:

输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:19

提示:

树中节点数目在范围 [1, 104] 之间。
1 <= Node.val <= 100

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int maxLevel = -1;
int sum = 0;
public:
int deepestLeavesSum(TreeNode* root) {
dfs(root, 0);
return sum;
}
void dfs(TreeNode *node, int level){
if (node == nullptr) {
return;
}
if (level > maxLevel) {
maxLevel = level;
sum = node->val;
} else if (level == maxLevel) {
sum += node->val;
}
dfs(node->left, level + 1);
dfs(node->right, level + 1);
}
};

1302. 层数最深叶子节点的和_数据结构_02