- BFS
层序遍历树,返回最后一次计算的结果
class Solution {
public int deepestLeavesSum(TreeNode root) {
List<TreeNode> list = new ArrayList<>();
int start = 0, end = 1, last = 1, cnt = 0;
list.add(root);
while(start < end){
cnt = 0;
while(start < last){
TreeNode node = list.get(start++);
cnt += node.val;
if(node.left != null){
list.add(node.left);
end++;
}
if(node.right != null){
list.add(node.right);
end++;
}
}
last = end;
}
return cnt;
}
}
- DFS
维护最大的层数maxLevel和返回值sum。如果当前层数大于maxLevel,那么更新maxLevel,并将sum赋值为root.val。如果当前层数等于maxLevel,那么sum加上root.val
class Solution {
int maxLevel = -1, sum = 0;
public int deepestLeavesSum(TreeNode root) {
dfs(root, 0);
return sum;
}
public void dfs(TreeNode root, int level){
if(root == null) return;
if(level > maxLevel){
maxLevel = level;
sum = root.val;
}else if(level == maxLevel){
sum += root.val;
}
dfs(root.left, level+1);
dfs(root.right, level+1);
}
}
标签:node,level,maxLevel,sum,leetcode1302,层数,root,节点
From: https://www.cnblogs.com/xzh-yyds/p/16594902.html