这是悦乐书的第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实现)的更多相关文章

  1. 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 ...

  2. 【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 ...

  3. 【LeetCode】637. Average of Levels in Binary Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:BFS 日期 题目地址:ht ...

  4. LeetCode 637. 二叉树的层平均值(Average of Levels in Binary Tree)

    637. 二叉树的层平均值 637. Average of Levels in Binary Tree LeetCode637. Average of Levels in Binary Tree 题目 ...

  5. 637. Average of Levels in Binary Tree - LeetCode

    Question 637. Average of Levels in Binary Tree Solution 思路:定义一个map,层数作为key,value保存每层的元素个数和所有元素的和,遍历这 ...

  6. 【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 ...

  7. LeetCode算法题-Convert Sorted Array to Binary Search Tree(Java实现)

    这是悦乐书的第166次更新,第168篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第25题(顺位题号是108).给定一个数组,其中元素按升序排序,将其转换为高度平衡的二叉 ...

  8. LeetCode算法题-Minimum Distance Between BST Nodes(Java实现-四种解法)

    这是悦乐书的第314次更新,第335篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第183题(顺位题号是783).给定具有根节点值的二叉搜索树(BST),返回树中任何两个 ...

  9. LeetCode算法题-Maximum Product of Three Numbers(Java实现)

    这是悦乐书的第275次更新,第291篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第143题(顺位题号是628).给定一个整数数组,从其中找出三个数,使得乘积最大.例如: ...

随机推荐

  1. Docker 删除所有无名称的镜像(悬空镜像)

    我们在build镜像的过程中,可能会产生一些临时的不具有名称也没有作用的镜像他们的名称一般都是<none>,我们可以执行下面的命令将其清除掉: docker rmi $(docker im ...

  2. redis 系列11 列表对象

    一. 列表对象概述 Redis列表是简单的字符串列表,按照插入顺序排序.你可以添加一个元素到列表的头部(左边)或者尾部(右边).一个列表最多可以包含 232 - 1 个元素 (4294967295, ...

  3. Chapter 5 Blood Type——31

    I stood carefully, and I was still fine. He held the door for me, his smile polite but his eyes mock ...

  4. Chapter 5 Blood Type——10

    "What?" “什么?” "Your boyfriend seems to think I'm being unpleasant to you — he's debat ...

  5. 初学Java Web(6)——JSP学习总结

    为什么要学习 JSP Servlet 的短板: Servlet 的出现,是为了解决动态输出网页的问题. 虽然这样做目的能达到,但是存在一些缺陷: 在 Servlet 输出网页片段非常恶心 (可读性差, ...

  6. Linux 中Ctrl + s 的作用

    在Linux下使用vim编辑程序时,常常会习惯性的按下Ctrl + s保存文件内容.殊不知,这一按不紧,整个终端再也不响应了. 事实上Ctrl + s在终端下是有特殊用途的,那就是暂停该终端,这个功能 ...

  7. kubernetes进阶之二:概述

    一:kubernetes是什么 Kubernetes一个用于容器集群的自动化部署.扩容以及运维的开源平台.通过Kubernetes,你可以快速有效地响应用户需求;快速而有预期地部署你的应用; 极速地扩 ...

  8. 【MongoDB】MongoDB环境配置

    软件下载与安装 1.mongDB下载,可到官网下载,我用的是3.4.6版本.可以放到任意目录下,我的MongDB安装目录为 D:\software\small_softeware\MongoDB 2. ...

  9. nginx部署dotnet core站点

    步骤 aspnetcore程序端口号5001,实际外部端口号8001,相当于把8001收到的请求转发给5001. 把发布出来的文件全部丢掉 /var/www/JuXiangTou 里面去.可以用scp ...

  10. Linux之部署前后端分离项目

    首先得看我前两个博客,把python3,虚拟环境,mariadb数据库,redis数据库,nginx安装好. 一.创建一个虚拟环境 1,创建虚拟环境 mkvirtualenv zijin #创建了一个 ...