Java for LeetCode 102 Binary Tree Level Order Traversal
2024-08-30 05:45:40
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
解题思路:
前序遍历(BFS),使用一个Queue存储每层元素即可,JAVA实现如下:
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (root == null)
return list;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (queue.size() != 0) {
List<Integer> alist = new ArrayList<Integer>();
for (TreeNode child : queue)
alist.add(child.val);
list.add(new ArrayList<Integer>(alist));
Queue<TreeNode> queue2=queue;
queue=new LinkedList<TreeNode>();
for(TreeNode child:queue2){
if (child.left != null)
queue.add(child.left);
if (child.right != null)
queue.add(child.right);
}
}
return list;
}
最新文章
- 微信jsApI及微信分享对应在手机浏览器的调用总结。
- NOIP复赛
- onblur鼠标失去焦点事件
- 使用Visual Studio Code开发AngularJS应用
- http://jingyan.baidu.com/article/636f38bb3eb78ad6b8461082.html
- pdmreader支持读取xml格式的pdm文件,无法读取二进制格式的pdm文件。
- redis使用场景
- 【C#编程基础学习笔记】4---Convert类型转换
- 【ThinkingInC++】53、构造函数,析构函数,全局变量
- List和ArrayList之间转换的例子
- 前端开发 Grunt 之 Connect详解
- 队列工厂之RedisMQ
- vue-router路由参数刷新消失的问题
- 配置Meld为git的默认比较工具
- [supervisor] 使用小记(入门教程)
- google搜索引擎使用
- 132.leecode-Palindrome Partitioning II
- 切换tab页
- npm安装包卡住不动的解决
- PHP关于=>;和->;以及::的用法
热门文章
- 【Maven】3.使用IntelliJ IDEA 使用本地搭建的maven私服,而不是使用默认的maven设置
- 【2048小游戏】——原生js爬坑之遍历算法显示二维数组内容
- SSO单点登录系列1:cas客户端源码分析cas-client-java-2.1.1.jar
- bbed初体验
- 常见CSS两栏式布局
- window.location.href重定向 不会触发webview
- ExtJS4 自己主动生成控制grid的列显示、隐藏的checkbox
- 在VS2013中打开Nuget
- HTTP基础(分析两个例子)
- JQuery EasyUI DataGrid动态合并单元格