Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Given binary tree {3,9,20,#,#,15,7},

    3
/ \
9 20
/ \
15 7

return

[
[3],
[9,20],
[15,7]
] For the problem given I decided to use BFS, however, the trick is to remember the number of nodes in same level before traversal.
So utilizing queue.size() before remove all the nodes in the same level. Utilized ArrayList to implement the queue. See code below:
 /**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/ public class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// write your code here
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>> ();
if (root == null ){
return result;
}
BFS(root,result);
return result;
}
/*At first I was trying to use BFS but I have no idea how to get all nodes in same layer to outputh to one list until I saw some answer from jiuzhang suanfa. It is obviously that the number of nodes is the queue's size before offerl()
implemented the queue by using linkedList*/
public void BFS (TreeNode root, ArrayList<ArrayList<Integer>> lists) {
ArrayList<TreeNode> queue = new ArrayList<TreeNode> ();
queue.add(root);
int maxDepth=0;
while (!queue.isEmpty()) {
ArrayList<Integer> list = new ArrayList<Integer>();
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode curr = queue.remove(0);
list.add(curr.val);
if (curr.left != null) {
queue.add(curr.left);
}
if (curr.right != null) {
queue.add(curr.right);
}
}
lists.add(list);
}
} }

最新文章

  1. 《OOC》笔记(1)——C语言const、static和extern的用法
  2. OC-苹果官方文档
  3. Invalid escape sequence(valid ones are \b \t \n \f \r \&quot; \&#39; \\)
  4. jsp学习(二)
  5. 模拟器的tableView的分割线不显示
  6. 故障模块名称: mso.dll
  7. C程序设计语言练习题1-6
  8. S3C2440 驱动程序开发
  9. 【转】Ubuntu 修改hosts
  10. android实现点击短链接进入应用 并获得整个连接的内容
  11. CCIE-MPLS VPN-实验手册(下卷)
  12. Chrome游览器使用时,修改文件和网页刷新后,不能显示效果
  13. 由清除float原理到BFC
  14. 【Vuex】vuex基本介绍与使用
  15. 森林防火应急指挥GIS系统森林防火监测预警系统
  16. 【地图功能开发系列:二】根据地址名称通过百度地图API查询出坐标
  17. 在vue项目中mock数据
  18. 前端自动化构建工具 gulp 学习笔记 一、
  19. SpringBoot图片上传
  20. python之路--动态传参,作用域,函数嵌套

热门文章

  1. Count Primes - LeetCode
  2. 里面的div怎么撑开外面的div让高度自适应
  3. Java处理excel文件
  4. (原创)LAMP搭建之一:图解如何安装并检查LAMP
  5. Eclipse SVN 安装步骤
  6. ubuntu 安装eclipse,adt,android sdk,离线
  7. ANSI C与GNU C
  8. 在eclipse中导入weka(小白在路上)
  9. 分布式系统中一些主要的副本更新策略——Dynamo/Cassandra/Riak同时采取了主从式更新的同步+异步类型,以及任意节点更新的策略。
  10. 困扰我多年的Connection reset问题