Get the list of list of keys in a given binary tree layer by layer. Each layer is represented by a list of keys and the keys are traversed from left to right.

Examples

5

/    \

3        8

/   \        \

1     4        11

the result is [ [5], [3, 8], [1, 4, 11] ]

Corner Cases

  • What if the binary tree is null? Return an empty list of list in this case.

How is the binary tree represented?

We use the level order traversal sequence with a special symbol "#" denoting the null node.

For Example:

The sequence [1, 2, 3, #, #, 4] represents the following binary tree:

1

/   \

2     3

/

4

/**
* public class TreeNode {
* public int key;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int key) {
* this.key = key;
* }
* }
*/
public class Solution {
public List<List<Integer>> layerByLayer(TreeNode root) {
// Write your solution here
// use BFS to solve this, thus, we use queue to maintain the nodes that we have seen but haven't deal with,
// and for each layer, we maintain a List to store all keys in this layer
// the tree can be null, then we return a List contains nothing
// the number of the elements in a single layer is less than Integer.MAX_VALUE
List<List<Integer>> res = new ArrayList<>();
if(root==null){
return res;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(q.size()>0){
int size = q.size();
List<Integer> layer = new ArrayList<>();
for(int i=0; i<size; i++){
TreeNode cur = q.poll();
if(cur!=null){
layer.add(cur.key);
}
if(cur.left!=null){
q.offer(cur.left);
}
if(cur.right!=null){
q.offer(cur.right);
}
}
res.add(layer);
}
return res;
}
}

最新文章

  1. (转)C# Enum,Int,String的互相转换 枚举转换
  2. Touch ID 实现
  3. ExtJS基础知识总结:常用控件使用方式(一)
  4. 如何删除NSDictionary或NSArray中的NSNull
  5. Selenium WebDriver 之 PageObjects 模式 by Example
  6. 转 Windows+VS2013爆详细Caffe编译安装教程
  7. DEV GridControl TableView隔行换色/奇偶行换色
  8. hibernate内部测试题(附赠答案)
  9. readonly背景色(css)
  10. zzulioj 1907小火山的宝藏交易(dfs记忆化搜索)
  11. JS基础知识(-)
  12. shell动态解析sql的binlog
  13. TamperData火狐插件启用
  14. linux grep常用参数
  15. 汉子英文同行 连续英文不折行断行 的问题 兼容FIREFOX浏览器CSS
  16. win10使用python开发工具pycharm首次安装配置
  17. precmd:6: job table full or recursion limit exceeded
  18. CentOs7.5安装PostgreSQL11
  19. GET 和 POST 的区别 以及为什么 GET请求 比 POST请求 更快
  20. css js 兼容问题

热门文章

  1. C - Perform the Combo
  2. Python系统模块os.py和sys.py常用函数
  3. 【PS】PS如何删除图片中的白字
  4. POD一些概念
  5. VSCode+EIDE开发CH32V系列RISC-V MCU
  6. esp8266 -rtos-sdk-vscode-config
  7. vue3导出功能
  8. 关于给widget添加属性
  9. git的基本操作(一)
  10. vue高级进阶( 三 ) 组件高级用法及最佳实践