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;
}

最新文章

  1. 微信jsApI及微信分享对应在手机浏览器的调用总结。
  2. NOIP复赛
  3. onblur鼠标失去焦点事件
  4. 使用Visual Studio Code开发AngularJS应用
  5. http://jingyan.baidu.com/article/636f38bb3eb78ad6b8461082.html
  6. pdmreader支持读取xml格式的pdm文件,无法读取二进制格式的pdm文件。
  7. redis使用场景
  8. 【C#编程基础学习笔记】4---Convert类型转换
  9. 【ThinkingInC++】53、构造函数,析构函数,全局变量
  10. List和ArrayList之间转换的例子
  11. 前端开发 Grunt 之 Connect详解
  12. 队列工厂之RedisMQ
  13. vue-router路由参数刷新消失的问题
  14. 配置Meld为git的默认比较工具
  15. [supervisor] 使用小记(入门教程)
  16. google搜索引擎使用
  17. 132.leecode-Palindrome Partitioning II
  18. 切换tab页
  19. npm安装包卡住不动的解决
  20. PHP关于=&gt;和-&gt;以及::的用法

热门文章

  1. 【Maven】3.使用IntelliJ IDEA 使用本地搭建的maven私服,而不是使用默认的maven设置
  2. 【2048小游戏】——原生js爬坑之遍历算法显示二维数组内容
  3. SSO单点登录系列1:cas客户端源码分析cas-client-java-2.1.1.jar
  4. bbed初体验
  5. 常见CSS两栏式布局
  6. window.location.href重定向 不会触发webview
  7. ExtJS4 自己主动生成控制grid的列显示、隐藏的checkbox
  8. 在VS2013中打开Nuget
  9. HTTP基础(分析两个例子)
  10. JQuery EasyUI DataGrid动态合并单元格