LeetCode算法题-Average of Levels in Binary Tree(Java实现)
这是悦乐书的第277次更新,第293篇原创
01 看题和准备
今天介绍的是LeetCode算法题中Easy级别的第145题(顺位题号是637)。给定一个非空二叉树,以数组的形式返回每一层节点值之和的平均值。例如:
3
/ \
9 20
/ \
15 7
输出:[3,14.5,11]
说明:第一层上的节点的平均值为3,第二层上的节点的平均值为14.5,第三层上的节点的平均值为11.因此返回[3,14.5,11]。
注意:节点值的范围在32位有符号整数的范围内。
本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。
02 第一种解法
使用广度优先算法(BFS)。使用队列来实现,在遍历节点的时候,使用了两层循环,外层控制层数,内层计算每一层的节点值之和,出了内层循环后,在外层循环里计算平均值,将平均值添加进数组中。其中有一点需要注意,计算节点值之和时,需要使用long类型,避免溢出。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list = new ArrayList<Double>();
if (root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
// 控制层数,其大小就是当前层数中包含的节点个数
int size = queue.size();
int count = 0;
// 使用long类型,避免溢出
long sum = 0;
// 处理每一层的节点值
while (size > 0) {
TreeNode temp = queue.poll();
count++;
if (temp != null) {
sum += temp.val;
}
if (temp != null && temp.left != null) {
queue.offer(temp.left);
}
if (temp != null && temp.right != null) {
queue.offer(temp.right);
}
size--;
}
// 计算平均值,添加进数组
list.add(sum*1.0d/count);
}
return list;
}
}
03 第二种解法
使用深度优先算法(DFS)。在使用深度优先算法时,需要先将每一层的节点值之和单独算出来,同时还要存储每一层的节点个数,借助递归算法实现,在得到两组数据后,再使用一次循环,计算每一层的平均值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
// 存放每一层的节点值总和
List<Double> list = new ArrayList<Double>();
if (root == null) {
return list;
}
// 存放每层节点个数
List<Integer> count = new ArrayList<Integer>();
dfs(0, root, list, count);
// 计算平均值
for (int i=0; i<list.size(); i++) {
list.set(i, list.get(i)/count.get(i));
}
return list;
}
public void dfs(int deep, TreeNode root, List<Double> list, List<Integer> count) {
if (root == null) {
return ;
}
// 判断是否还在当前此层内
if (deep < list.size()) {
list.set(deep, list.get(deep)+root.val);
count.set(deep, count.get(deep)+1);
} else {
// 新的一层
list.add(1.0*root.val);
count.add(1);
}
// 递归调用剩下的节点
dfs(deep+1, root.left, list, count);
dfs(deep+1, root.right, list, count);
}
}
04 小结
此题本质上是对二叉树的BFS、DFS算法的考察,在普通遍历节点的基础上,分层处理节点数据。
算法专题目前已日更超过四个月,算法题文章145+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。
以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!
LeetCode算法题-Average of Levels in Binary Tree(Java实现)的更多相关文章
- leetcode算法: Average of Levels in Binary Tree
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an ...
- 【leetcode】637. Average of Levels in Binary Tree
原题 Given a non-empty binary tree, return the average value of the nodes on each level in the form of ...
- 【LeetCode】637. Average of Levels in Binary Tree 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:BFS 日期 题目地址:ht ...
- LeetCode 637. 二叉树的层平均值(Average of Levels in Binary Tree)
637. 二叉树的层平均值 637. Average of Levels in Binary Tree LeetCode637. Average of Levels in Binary Tree 题目 ...
- 637. Average of Levels in Binary Tree - LeetCode
Question 637. Average of Levels in Binary Tree Solution 思路:定义一个map,层数作为key,value保存每层的元素个数和所有元素的和,遍历这 ...
- 【Leetcode_easy】637. Average of Levels in Binary Tree
problem 637. Average of Levels in Binary Tree 参考 1. Leetcode_easy_637. Average of Levels in Binary T ...
- LeetCode算法题-Convert Sorted Array to Binary Search Tree(Java实现)
这是悦乐书的第166次更新,第168篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第25题(顺位题号是108).给定一个数组,其中元素按升序排序,将其转换为高度平衡的二叉 ...
- LeetCode算法题-Minimum Distance Between BST Nodes(Java实现-四种解法)
这是悦乐书的第314次更新,第335篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第183题(顺位题号是783).给定具有根节点值的二叉搜索树(BST),返回树中任何两个 ...
- LeetCode算法题-Maximum Product of Three Numbers(Java实现)
这是悦乐书的第275次更新,第291篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第143题(顺位题号是628).给定一个整数数组,从其中找出三个数,使得乘积最大.例如: ...
随机推荐
- 从锅炉工到AI专家(1)
序言 标题来自一个很著名的梗,起因是知乎上一个问题:<锅炉设计转行 AI,可行吗?>,后来就延展出了很多类似的问句,什么"快递转行AI可行吗?"."xxx转行 ...
- C#3.0 Lamdba表达式与表达式树
Lamdba表达式与表达式树 Lamdba表达式 C#2.0中的匿名方法使得创建委托变得简单起来,甚至想不到还有什么方式可以更加的简化,而C#3.0中的lamdba则给了我们答案. lamdba的行为 ...
- [NewLife.XCode]对象字典缓存(百万军中取敌首级)
NewLife.XCode是一个有10多年历史的开源数据中间件,支持nfx/netcore,由新生命团队(2002~2019)开发完成并维护至今,以下简称XCode. 整个系列教程会大量结合示例代码和 ...
- Typora - Markdown 语法说明
Typora 是 Windows 下最好的 Markdown 编辑器!不接受反驳~ 导图 快捷键标题:Ctrl + 数字 Ctrl + 123456 代表 H1-H6 级标题Ctrl + 0 恢复普通 ...
- leetcode — palindrome-partitioning
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Source : https://o ...
- .NetCore部署至IIS
部署教程 操作系统要求 Windows 7 或更高版本 Windows Server 2008 R2 或更高版本 依赖的组件 Runtime & Hosting Bundle 可以选择.NET ...
- 解读经典《C#高级编程》第七版 Page100-107.继承.Chapter4
前言 本章节继续讲实现继承. 实现继承 密封类和密封方法 密封类和方法的概念很简单,就是为了不允许类和方法被继承和扩展.不允许扩展一般的原因有: 如果类或者方法被扩展,可能会导致类库执行错误 因为版权 ...
- Windows已遇到关键问题,将在一分钟后自动重新启动,请立即保存工作
Windows已遇到关键问题,将在一分钟后自动重新启动,请立即保存工作 1. 把电脑右下角网络断开 2.同时按 "WIN+R" 打开“运行”命令窗口 输入“cmd”命令,按回车键“ ...
- Promise杂记
更好的阅度体验 前言 API Promise特点 状态跟随 V8中的async await和Promise 实现一个Promise 参考 前言 作为一个前端开发,使用了Promise一年多了,一直以来 ...
- .Net中Log4Net的使用
2018-08-23 .Net中Log4Net的使用 一.log4net 分类型记录日志存放多个日志文件 1.在webconfig里添加配置 1.1 在<configSections> 中 ...