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

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

目录

题目

思路一(迭代)

采用广度优先搜索(BFS)的方法,利用队列的先进先出特性遍历树节点。

  • BFS广度优先搜索
  • 使用队列来实现先进先出的特性

代码

import java.util.*;  public 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),因为在最坏情况下队列会保存所有节点。

思路二(递归)

采用深度优先搜索(DFS)的方法,递归地遍历树节点,并将每一层的节点值按层存储。

  • DFS深度优先搜索
  • 递归函数中使用索引来表示当前处理的层数
  • 每次递归调用时,将当前节点值添加到对应的层中

代码

import java.util.*;  public class Solution {      public List levelOrder(TreeNode root) {          List res = new LinkedList<>();          if (root == null) {              return res;          }          dfs(1, res, root);          return res;      }      private 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/

你可能感兴趣的文章
PIGS POJ 1149 网络流
查看>>
PIL Image对图像进行点乘,加上常数(等像素操作)
查看>>
PIL.Image、cv2的img、bytes相互转换
查看>>
PIL.Image进行图像融合显示(Image.blend)
查看>>
Pillow lacks the JPEG 2000 plugin
查看>>
ping 全网段CMD命令
查看>>
ping 命令的七种用法,看完瞬间成大神
查看>>
Pinia:$patch的使用场景
查看>>
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>
pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
查看>>
pip install mysqlclient报错
查看>>
pip install 出现报asciii码错误的解决
查看>>
pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
查看>>
pip 下载慢
查看>>
pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
查看>>