链接

https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/
难度: #简单

题目

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

**例如: **
给定二叉树: [3,9,20,null,null,15,7],

3/ \9  20/  \15   7

返回其层次遍历结果:

[[3],[9,20],[15,7]
]

提示:节点总数 <= 1000

代码框架

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {}
}

题目解析

解答思路1:
递归函数解法,
每次递归打印同一层的节点,
然后找出这一层节点的所有下一层的节点,
继续进行递归。

解答思路2:
递归函数解法,
在递归过程中确定元素所在层数,
然后按照层数加入到结果对应的集合中。

解答思路3:
使用辅助队列cur和next,
分别保存当前一层的节点和下一层的节点,
把cur当前一层打印出来,
然后把下一层的节点保存到next,
当cur遍历结束时,
把next赋值给cur,
再次开始打印新一层的节点,
直到cur为空时结束循环。

解答思路4:
使用一个辅助队列,
当队列不为空时,
记录下当前队列的元素个数 ,
这些元素都是属于同一层的,
打印这些同层的元素,
然后把当前元素不为空的左右节点加入队列,
完成后开始打印下一层元素,
同样记录当前队列的元素个数。

测试用例

package edu.yuwen.sowrd.num32_II.solution;import java.util.List;import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;import edu.yuwen.sowrd.entity.TreeNode;
import edu.yuwen.sowrd.num32_II.sol4.Solution;public class SolutionTest {/*** 给定二叉树: [3,9,20,null,null,15,7]* 3* / \*9  20*   / \*  15  7* 返回[3,9,20,15,7]*/@Testpublic void testCase1() {Solution solution = new Solution();TreeNode node1 = new TreeNode(3);TreeNode node2 = new TreeNode(9);TreeNode node3 = new TreeNode(20);TreeNode node4 = new TreeNode(15);TreeNode node5 = new TreeNode(7);node1.left = node2;node1.right = node3;node3.left = node4;node3.right = node5;TreeNode root = node1;List<List<Integer>> res = solution.levelOrder(root);int[][] expected = { { 3 }, { 9, 20 }, { 15, 7 } };for (int i = 0; i < expected.length; i++) {int[] resArray = res.get(i).stream().mapToInt(Integer::intValue).toArray();Assertions.assertArrayEquals(expected[i], resArray);}}
}

解答1

package edu.yuwen.sowrd.num32_II.sol1;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;import edu.yuwen.sowrd.entity.TreeNode;public class Solution {List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> levelOrder(TreeNode root) {if (root == null) {return res;}List<TreeNode> nodes = Collections.singletonList(root);recurve(nodes);return res;}private void recurve(List<TreeNode> nodes) {// 没有节点需要处理了,则结束递归if (nodes == null || nodes.size() == 0) {return;}// 打印当前同一层的节点List<Integer> level = new ArrayList<>();// 找出所有的下一层节点List<TreeNode> nextNodes = new ArrayList<>();for (TreeNode node : nodes) {level.add(node.val);if (node.left != null) {nextNodes.add(node.left);}if (node.right != null) {nextNodes.add(node.right);}}res.add(level);// 递归处理下一层节点recurve(nextNodes);}
}

解答2 推荐

package edu.yuwen.sowrd.num32_II.sol2;import java.util.ArrayList;
import java.util.List;import edu.yuwen.sowrd.entity.TreeNode;public class Solution {List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> levelOrder(TreeNode root) {if (root == null) {return res;}// root节点在0层recurve(root, 0);return res;}/*** 当前节点及所在层*/private void recurve(TreeNode node, int k) {// 节点为空时,结束递归if (node == null) {return;}// k大于结果集的最大索引,初始化新的一层集合if (k > res.size() - 1) {res.add(new ArrayList<>());}// 当前节点记录到当前层对应的集合List<Integer> level = res.get(k);level.add(node.val);recurve(node.left, k + 1);recurve(node.right, k + 1);}
}

解答3

package edu.yuwen.sowrd.num32_II.sol3;import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;import edu.yuwen.sowrd.entity.TreeNode;public class Solution {List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> levelOrder(TreeNode root) {if (root == null) {return res;}// 当前层节点Queue<TreeNode> cur = new LinkedList<>();// 下一层节点Queue<TreeNode> next = new LinkedList<>();// 使用头结点初始化当前层cur.offer(root);// 当前层为空时,结束循环while (!cur.isEmpty()) {List<Integer> level = new ArrayList<>();while (!cur.isEmpty()) {TreeNode node = cur.poll();level.add(node.val);if (node.left != null) {next.offer(node.left);}if (node.right != null) {next.offer(node.right);}}res.add(level);// 将next和cur交换Queue<TreeNode> temp = cur;cur = next;next = temp;}return res;}
}

解答4

package edu.yuwen.sowrd.num32_II.sol4;import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;import edu.yuwen.sowrd.entity.TreeNode;public class Solution {List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> levelOrder(TreeNode root) {if (root == null) {return res;}// 队列及初始化Queue<TreeNode> q = new LinkedList<>();q.offer(root);while (!q.isEmpty()) {// 当前层的元素数量int count = q.size();// 记录当前层的元素List<Integer> level = new ArrayList<>(count);for (int i = 0; i < count; i++) {TreeNode node = q.poll();level.add(node.val);if (node.left != null) {q.offer(node.left);}if (node.right != null) {q.offer(node.right);}}/*** 更优的写法:* for (int i = q.siez(); i >0; i--)*/res.add(level);}return res;}
}

http://www.taodudu.cc/news/show-1250929.html

相关文章:

  • 32 - III. 从上到下打印二叉树 III
  • 26. 树的子结构
  • PostgreSQL数据库密码
  • SpringBoot中使用Hibernate Validator校验工具类
  • 28. 对称的二叉树
  • 解决tomcat的undeploy
  • 解决eclipse出现The superclass javax.servlet.http.HttpServlet was not found on the Java Build Path
  • 下载安装neo4j
  • vue-drag-resize实线页面的拖拽与缩放
  • 解决IDEA不能编译XML文件
  • 播放视频和音频文件java
  • 实时获取屏幕大小
  • vue部分样式无法修改
  • vue中根据搜索内容跳转到页面指定位置
  • Duplicate entry ‘‘ for key ‘***‘
  • transferto遇到的问题java.io.FileNotFoundException: C:\Users\Administrator\AppData\Local\Temp
  • Spring的jar包下载
  • *** is required and cannot be removed from the server
  • Tomcat 服务器介绍和使用
  • 第一个 Web 程序
  • Servlet 介绍
  • 集成 Tomcat、 Servlet 的生命周期
  • Request 对象、重定向、请求转发
  • Cookie 学习
  • ServletContext对象、ServletConfig对象
  • sevlet中web.xml 文件
  • 过滤器、监听器
  • El 表达式、jstl学习
  • cookie与session详解、url地址重写
  • 命名规范、MVC 开发模式

32 - II. 从上到下打印二叉树 II相关推荐

  1. 【LeetCode】剑指 Offer 32 - II. 从上到下打印二叉树 II

    [LeetCode]剑指 Offer 32 - II. 从上到下打印二叉树 II 文章目录 [LeetCode]剑指 Offer 32 - II. 从上到下打印二叉树 II 一.层序遍历 BFS 一. ...

  2. 剑指offer:面试题32 - II. 从上到下打印二叉树 II

    题目:从上到下打印二叉树 II 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行. 例如: 给定二叉树: [3,9,20,null,null,15,7], 3    / \ ...

  3. 【简洁+注释】剑指 Offer 32 - II. 从上到下打印二叉树 II

    立志用最少的代码做最高效的表达 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行. 例如: 给定二叉树: [3,9,20,null,null,15,7], 返回其层次遍历结果 ...

  4. 剑指 Offer 32 - II. 从上到下打印二叉树 II

    2020-06-22 1.题目描述 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行. 2.题解 广度优先搜索,即层次遍历即可 3.代码 /*** Definition fo ...

  5. 剑指offer面试题32 - II. 从上到下打印二叉树 II(二叉树)(BFS)

    题目描述 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行. 思路 详见链接 代码 class Solution:def levelOrder(self,root:TreeN ...

  6. JZ32变形~剑指 Offer 32 - II. 从上到下打印二叉树 II

    放假不学习/上班,学习不放假.放假当然是不能学习或工作啦

  7. leetcode 打印_剑指 Offer 32 - III 从上到下打印二叉树 III - leetcode 剑指offer

    题目难度: 中等 原题链接 今天继续更新剑指 offer 系列, 这道题相比昨天那道题多了个每层打印方向不同的需求, 聪明的你想到应该如何实现了吗? 老样子晚上 6 点 45 分准时更新公众号 每日精 ...

  8. 32 - I. 从上到下打印二叉树

    链接 https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/ 难度: #中等 题目 从上到下打印出二叉树 ...

  9. 从上到下打印二叉树 II

    从上到下打印二叉树 II 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行. 例如: 给定二叉树: [3,9,20,null,null,15,7], 3/ \9 20/ \1 ...

最新文章

  1. R语言dplyr包mutate_if函数修改所有满足条件的数据列的内容实战
  2. python画树叶-使用Python turtle画分形树叶图
  3. Java定位CPU使用高问题--转载
  4. Spring中你不知道的注入方式
  5. LVGL-v8.1 demo win32 VS2017工程
  6. 燃烧学往年精选真题解析2018-01-01
  7. [SPS2010] 使用心得 7 - ebook for Installation
  8. java网络爬虫连接超时解决[实战程序]
  9. Buffer.concat()
  10. 利用反射实现工厂模式
  11. Unity中资源打包成Assetsbundle的资料整理
  12. data fastboot 擦除_fastboot是什么?如何解锁fastboot?
  13. 96道前端面试题+前端常用算法
  14. RAR及ZIP压缩文件解压提示文件损坏或无法解压原因及修复办法全解析
  15. cesium面积测量
  16. iphone/ios兼容问题
  17. 怎样修改mysql密码
  18. Linux进程通信-管道
  19. 【转】前端——实用UI组件库
  20. Java二维数组声明与初始化

热门文章

  1. 20145236《网络对抗》进阶实验——64位Ubuntu 17.10.1 ROP攻击
  2. phpexcel导出后乱码或者是打不开文件必须修复的问题
  3. 糍粑大叔的独游之旅-战斗!之弹道实现(上)
  4. Dapper试用简例
  5. 使用 Adobe AIR 管理 WordPress 评论
  6. PCL 学习(2)——基本数据类型与点云数据拼接
  7. ros构建机器人运动学模型_机器人开源控制软件 OROCOS
  8. 禁止吸烟(字符串替换)
  9. MYSQL添加约束的两种方法
  10. 如何在PHP里面连接数据库?