标签:++ offer 示例 lis sem ret hash math queue
给你一棵二叉树,请你返回层数最深的叶子节点的和。
示例:
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
提示:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/deepest-leaves-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
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);
}
}
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;
}
标签:++ offer 示例 lis sem ret hash math queue
原文地址:https://www.cnblogs.com/angelica-duhurica/p/12248752.html