1302-层数最深叶子节点的和
Posted angelica-duhurica
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1302-层数最深叶子节点的和相关的知识,希望对你有一定的参考价值。
1302-层数最深叶子节点的和
给你一棵二叉树,请你返回层数最深的叶子节点的和。
示例:
输入: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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
DFS
private int deepest = 0;
private Map<Integer, Integer> map = new HashMap<>();
public int deepestLeavesSum(TreeNode root) {
scan(root, 0);
return map.getOrDefault(deepest, 0);
}
private void scan(TreeNode root, int depth) {
deepest = Math.max(deepest, depth);
if(root.left == null && root.right == null) {
map.put(depth, map.getOrDefault(depth, 0) + root.val);
}
if(root.left != null) {
scan(root.left, depth + 1);
}
if(root.right != null) {
scan(root.right, depth + 1);
}
}
改进:缩小map
private int deepest = 0;
private Map<Integer, Integer> map = new HashMap<>();
public int deepestLeavesSum(TreeNode root) {
scan(root, 0);
return map.getOrDefault(deepest, 0);
}
private void scan(TreeNode root, int depth) {
if(depth > deepest) {
deepest = depth;
// 说明之前存储的数据无用
map.clear();
}
if(depth == deepest && root.left == null && root.right == null) {
map.put(depth, map.getOrDefault(depth, 0) + root.val);
}
if(root.left != null) {
scan(root.left, depth + 1);
}
if(root.right != null) {
scan(root.right, depth + 1);
}
}
进一步改进:不使用map,直接用int全局变量存储结果
private int deepest = 0;
private int sum = 0;
public int deepestLeavesSum(TreeNode root) {
scan(root, 0);
return sum;
}
private void scan(TreeNode root, int depth) {
if(depth > deepest) {
deepest = depth;
sum = 0;
}
if(depth == deepest && root.left == null && root.right == null) {
sum += root.val;
}
if(root.left != null) {
scan(root.left, depth + 1);
}
if(root.right != null) {
scan(root.right, depth + 1);
}
}
BFS
public int deepestLeavesSum(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int res = 0;
while (!queue.isEmpty()) {
res = 0;
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode tmp = queue.poll();
res += tmp.val;
if (tmp.left != null)
queue.offer(tmp.left);
if (tmp.right != null)
queue.offer(tmp.right);
}
}
return res;
}
以上是关于1302-层数最深叶子节点的和的主要内容,如果未能解决你的问题,请参考以下文章