给你一棵二叉树的根节点 root
,请你返回 层数最深的叶子节点的和 。
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:19
树中节点数目在范围 [1, 104] 之间。
1 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/deepest-leaves-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
记录每一层所有结点的和,每一次结束后,如果和不为零,更新ans,如果为0直接break。
- /**
- * 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 {
- public:
- int deepestLeavesSum(TreeNode* root) {
- int ans = 0;
- queue
q; - q.push(root);
- int depth = 0;
- while(q.size()) {
- int s = q.size();
- int sum = 0;
- while(s -- ) {
- auto t = q.front();
- q.pop();
- sum += t->val;
- if(t->left) q.push(t->left);
- if(t->right) q.push(t->right);
- }
- ans = sum;
- }
- return ans;
- }
- };