博客
关于我
力扣 - 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/

你可能感兴趣的文章
pt-archiver 归档历史数据及参数详解
查看>>
Pytest框架环境切换实战教程!赶快收藏
查看>>
python - 将字符串中的日期与今天的日期进行比较
查看>>
python ctypes库中动态链接库加载方式
查看>>
python datetime笔记
查看>>
python day10
查看>>
python file
查看>>
Python FileDialog获取文件夹路径不是文件
查看>>
python filter过滤器的使用_python基础知识分享:zip()、filter函数和reduce如何使用?...
查看>>
python flask 请求code 400, message Bad request version
查看>>
Python Flink Stateful函数入口上的Kafka键访问
查看>>
Python float - str - 浮动怪异
查看>>
Python Flower库:分布式任务管理与监控
查看>>
Python for 循环和迭代器行为
查看>>
Python For循环多次返回
查看>>
python frame_python3 selenium自动化 frame表单嵌套的切换方法
查看>>
Python ftplib - 指定端口
查看>>
Python furl库:一键搞定复杂URL操作
查看>>
Python GC 也会关闭文件吗?
查看>>
python gen_key.py 报错 提示找不到OpenSSL lib
查看>>