1.题目
给你一棵二叉树,请你返回层数最深的叶子节点的和。
示例:
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
提示:
树中节点数目在 1 到 10^4 之间。
每个节点的值在 1 到 100 之间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/deepest-leaves-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.我的题解
广度优先遍历,遍历的时候记录每一层的节点值之和,进入下一层时先将和清0,最后一次记录的和就是结果。
/**
* 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) {
queue<TreeNode *> q;
int res=0;
if(root)q.push(root);
while(!q.empty()){
res=0;
int len = q.size();
for(int i=0;i<len;i++){
if(q.front()->left)q.push(q.front()->left);
if(q.front()->right)q.push(q.front()->right);
res+=q.front()->val;
q.pop();
}
}
return res;
}
};
3.别人的题解
深度优先遍历也可,实现时将层数当做递归的参数传入。
需要记录两个变量,一个是当前得到的和,一个是当前树的最大深度。
/**
* 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 {
int sum=0;
int curDepth=-1;
public:
int deepestLeavesSum(TreeNode* root) {
dfs(root,0);
return sum;
}
void dfs(TreeNode * root ,int depth){
if(root==NULL)return;
if(depth==curDepth){sum+=root->val;}
else if(depth>curDepth){sum=root->val;curDepth=depth;}
dfs(root->left,depth+1);
dfs(root->right,depth+1);
}
};
4.总结与反思
(1)深度优先搜索递归实现简单,但耗时高;