题目描述:
给你一棵二叉树,请你返回层数最深的叶子节点的和。
示例:
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
提示:
树中节点数目在 1 到 10^4 之间。
每个节点的值在 1 到 100 之间。
方法1:
主要思路:解题汇总链接
(1)使用层次遍历,计算最后一行元素的和;
/**
* 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:
int deepestLeavesSum(TreeNode* root) {
if(root==NULL){
return 0;
}
queue<TreeNode*> q;
q.push(root);
int res=0;
//层次遍历
while(!q.empty()){
int cur_res=0;//统计当前层的和
int cur_size=q.size();
while(cur_size--){
root=q.front();
q.pop();
cur_res+=root->val;//统计当前结点
if(root->left){
q.push(root->left);
}
if(root->right){
q.push(root->right);
}
}
res=cur_res;//更新当前层
}
return res;
}
};