博客
关于我
力扣 - 102. 二叉树的层序遍历
阅读量:450 次
发布时间:2019-03-06

本文共 1387 字,大约阅读时间需要 4 分钟。

目录

题目

思路1(迭代)

  • BFS广度优先搜索
  • 用队列先进先出特性遍历

代码

class Solution {    public List
> levelOrder(TreeNode root) { List
> res = new LinkedList<>(); if (root == null) { return res; } Deque
queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { List
level = new LinkedList<>(); int size = queue.size(); while (size > 0) { TreeNode node = queue.poll(); level.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } size--; } res.add(level); } return res; }}

复杂度分析

  • 时间复杂度:\(O(N)\)
  • 空间复杂度:\(O(N)\)

思路2(递归)

  • DFS深度优先搜索
  • res.size() < index:每一层只能添加一个链表用来存储本层节点的值
  • 每次搜索遍历都将本节点添加道对应的层的位置

代码

class Solution {    public List
> levelOrder(TreeNode root) { List
> res = new LinkedList<>(); if (root == null) { return res; } dfs(1, res, root); return res; } public void dfs(int index, List
> res, TreeNode root) { if (root == null) { return; } // 每层只能添加一个链表 if (res.size() < index) { res.add(new LinkedList<>()); } // 将节点的值添加道本层的链表中 res.get(index-1).add(root.val); dfs(index+1, res, root.left); dfs(index+1, res, root.right); }}

复杂度分析

  • 时间复杂度:\(O(N)\)
  • 空间复杂度:\(O(h)\),其中 h 为树的高度

转载地址:http://lspyz.baihongyu.com/

你可能感兴趣的文章
mysql和oorcale日期区间查询【含左右区间问题】
查看>>
MYSQL和ORACLE的一些操作区别
查看>>
mysql和redis之间互相备份
查看>>
MySQL和SQL入门
查看>>
mysql在centos下用命令批量导入报错_Variable ‘character_set_client‘ can‘t be set to the value of ‘---linux工作笔记042
查看>>
Mysql在Linux运行时新增配置文件提示:World-wrirable config file ‘/etc/mysql/conf.d/my.cnf‘ is ignored 权限过高导致
查看>>
Mysql在Windows上离线安装与配置
查看>>
MySQL在渗透测试中的应用
查看>>
Mysql在离线安装时启动失败:mysql服务无法启动,服务没有报告任何错误
查看>>
Mysql在离线安装时提示:error: Found option without preceding group in config file
查看>>
MySQL基于SSL的主从复制
查看>>
Mysql基本操作
查看>>
mysql基本操作
查看>>
mysql基本知识点梳理和查询优化
查看>>
mysql基础
查看>>
Mysql基础 —— 数据基础操作
查看>>
mysql基础---mysql查询机制
查看>>
MySQL基础5
查看>>
MySQL基础day07_mysql集群实例-MySQL 5.6
查看>>
Mysql基础命令 —— 数据库、数据表操作
查看>>