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).给定一个整数数组,从其中找出三个数,使得乘积最大.例如: ...
随机推荐
- 开启 IPv6 新时代,升级后的 IPv6 厉害在哪?
IPv6,Internet Protocol Version 6,从字面翻译 “互联网协议第 6 版”,它是IETF设计的用于替代现行版本 IP 协议-IPv4 协议,被称作“下一代互联网协议”.早在 ...
- 【从零开始自制CPU之学习篇03】锁存器与触发器
本篇学习了两种锁存器:SR Latch和D Latch,一种触发器:D flip flop SR Latch:SR—锁存器 初始状态下,S和R都为0,Q和Q‘随机有一个为1另一个 为0(取决于电流速度 ...
- Python爬虫入门教程 39-100 天津市科技计划项目成果库数据抓取 scrapy
爬前叨叨 缘由 今天本来没有打算抓取这个网站的,无意中看到某个微信群有人问了一嘴这个网站,想看一下有什么特别复杂的地方,一顿操作下来,发现这个网站除了卡慢,经常自己宕机以外,好像还真没有什么特殊的.. ...
- 【Java基础】【04循环语句&方法】
04.01_Java语言基础(循环结构概述和for语句的格式及其使用) A:循环结构的分类 for,while,do...while B:循环结构for语句的格式: for(初始化表达式;条件表达式; ...
- Spring Boot 2.x(五):整合Mybatis-Plus
简介 Mybatis-Plus是在Mybatis的基础上,国人开发的一款持久层框架. 并且荣获了2018年度开源中国最受欢迎的中国软件TOP5 同样以简化开发为宗旨的Spring Boot与Mybat ...
- 内核中 xxx_initcall 的调用过程分析
内核版本:linux-4.19 上一篇文章提到了这段代码: arch_initcall_sync(of_platform_default_populate_init); 它的功能是完成 device_ ...
- 第17章 社区快速入门和模板 - Identity Server 4 中文文档(v1.0.0)
IdentityServer组织不维护这些示例.IdentityServer组织愉快地链接到社区模板,但不能对模板做出任何保证.请直接与作者联系. 17.1 各种ASP.NET核心安全样本 https ...
- 杭电ACM2009--求数列的和
求数列的和 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submi ...
- sql 参数化查询问题
一.正确案例 string name=“梅”; string sql="select * from test where Name like @Name"; //包含 梅Sql ...
- PHP数组array_multisort排序详解
今天特意再看了下官网的介绍,对它的多个数组的排序还是每台理解,找了些资料深入理解了下,在此总结下. PHP中array_multisort函数对多个数组或多维数组进行排序,关联(string)键名保持 ...