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).给定一个整数数组,从其中找出三个数,使得乘积最大.例如: ...
随机推荐
- 【Spark篇】---SparkStream初始与应用
一.前述 SparkStreaming是流式处理框架,是Spark API的扩展,支持可扩展.高吞吐量.容错的实时数据流处理,实时数据的来源可以是:Kafka, Flume, Twitter, Zer ...
- vue+cordova构建跨平台应用集成并使用Cordova plugin
安装 //安装 vue-cil npm install --global vue-cli //安装cordova npm i cordova -g cordova 新建项目 //新建cordova 项 ...
- 根据地址查询经纬度Js
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>根据地址查询经纬度</ ...
- C#版 - 226. Invert Binary Tree(剑指offer 面试题19) - 题解
版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - 2 ...
- JS 中 原生方法 (二) --- 数组 (修---添加ES6新增)
const arr = [1, 2, 3, 5, 'a', 'b'] /** * * length * 这个只能被 称之为 数组的原生属性, 返回 一个 number * arr.length */ ...
- ASP.NET页面之间的几种传值方法
首先是QueryString方法传值: QueryString是一种非常简单的传值方式,他可以将传送的值显示在浏览器的地址栏中.如果是传递一个或多个安全性要求不高或是结构简单的数值时,可以使用这个方法 ...
- ASP.NET Core DI 手动获取注入对象
ASP.NET Core DI 一般使用构造函数注入获取对象,比如在ConfigureServices配置注入后,通过下面方式获取: private IValueService _valueServi ...
- Markdown 文档生成工具
之前用了很多Markdown 文档生成工具,发现有几个挺好用的,现在整理出来,方便大家快速学习. loppo: 非常简单的静态站点生成器 idoc:简单的文档生成工具 gitbook:大名鼎鼎的文档协 ...
- leetcode — word-ladder-ii
import java.util.*; /** * Source : https://oj.leetcode.com/problems/word-ladder-ii/ * * * Given two ...
- Java开发笔记(七十八)面向对象的后门——反射
作为一门面向对象的编程语言,Java认为一切皆是对象,每个对象都能归属于某个类,甚至每个类均可提取出一种特殊的类型,即Class类型.早在前面介绍多态的时候,就提到每个类都存在独一无二的基因,通过比较 ...