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).给定一个整数数组,从其中找出三个数,使得乘积最大.例如: ...
随机推荐
- solr之环境配置四
Solr链接数据库(mysql,mssql) 一.链接mysql 1.使用DataImportHandler导入并索引数据,配置 $SOLR_HOME\core0\conf\solrconfig.xm ...
- 前端笔记之jQuery(上)加载函数的区别&对象&操作HTML/CSS&动画&选择器
一.jQuery简介 1.0 JavaScript编程比较恶心的地方 恶心1:选择元素麻烦,全线兼容的方法只有getElementById()和getElementsByTagName()两个.其他的 ...
- log4j2.yml配置文件
# https://blog.csdn.net/u010598111/article/details/80556437 # 共有8个级别,按照从低到高为:ALL < TRACE < DEB ...
- leetcode — recover-binary-search-tree
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util. ...
- [十]JavaIO之FilterInputStream FilterOutputStream
FilterInputStream FilterOutputStream都是装饰器模式中的Decorator抽象装饰角色 他们继承了各自的抽象构建InputStream 和OutputStream ...
- Web工作方式:浏览网页的时候发生了什么?
原文地址:https://wizardforcel.gitbooks.io/build-web-application-with-golang/content/03.1.html 我们平时浏览网页的时 ...
- DSAPI HTTP监听服务端与客户端
本文中,演示了使用DSAPI.网络相关.HTTP监听,快速建立服务端和客户端. HTTP监听服务端的作用,是监听指定计算机端口,以实现与IIS相同的解析服务,提供客户端的网页请求,当然,这不仅仅是应用 ...
- PhpStorm 安装ApiDebugger
ApiDebugger,是一个开源的接口调试IntelliJ IDEA插件,具有与IDEA一致的界面,无需切换程序即可完成网络API请求,让你的code更加沉浸式. 安装 File->Setti ...
- Java开发笔记(三十六)字符串的常用方法
不管是给字符串赋值,还是对字符串格式化,都属于往字符串填充内容,一旦内容填充完毕,则需开展进一步的处理.譬如一段Word文本,常见的加工操作就有查找.替换.追加.截取等等,按照字符串的处理结果异同,可 ...
- Linux基础(Ubuntu16.04):安装vim及配置
1.进入终端 Ctrl + Alt +T 出现终端窗口 2.输入命令: sudo apt-get install vim-gtk 3.验证是否成功 安装完vim后查看命令 vi tab键,就会关联出 ...