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

你可能感兴趣的文章
poj 2112 最优挤奶方案
查看>>
Qt编写自定义控件12-进度仪表盘
查看>>
poj 2186 Popular Cows :求能被有多少点是能被所有点到达的点 tarjan O(E)
查看>>
POJ 2186:Popular Cows Tarjan模板题
查看>>
POJ 2229 Sumsets(递推,找规律)
查看>>
poj 2236
查看>>
POJ 2243 Knight Moves
查看>>
POJ 2262 Goldbach's Conjecture
查看>>
POJ 2362 Square DFS
查看>>
poj 2386 Lake Counting(BFS解法)
查看>>
poj 2387 最短路模板题
查看>>
POJ 2391 多源多汇拆点最大流 +flody+二分答案
查看>>
POJ 2403
查看>>
poj 2406 还是KMP的简单应用
查看>>
POJ 2431 Expedition 优先队列
查看>>
Qt笔记——获取位置信息的相关函数
查看>>
POJ 2484 A Funny Game(神题!)
查看>>
POJ 2486 树形dp
查看>>
POJ 2488:A Knight&#39;s Journey
查看>>
SpringBoot为什么易学难精?
查看>>