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