给定一个二叉树,返回其按层次遍历的节点值。 (即zhu'ceng'de,从左到右访问)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果为:
[
  [3],
  [9,20],
  [15,7]
]
详见:https://leetcode.com/problems/binary-tree-level-order-traversal/description/

Java实现:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(root==null){
return res;
}
LinkedList<TreeNode> que=new LinkedList<TreeNode>();
que.offer(root);
int curNode=1;
ArrayList<Integer> list=new ArrayList<Integer>();
while(!que.isEmpty()){
root=que.poll();
--curNode;
if(root.left!=null){
que.offer(root.left);
}
if(root.right!=null){
que.offer(root.right);
}
list.add(root.val);
if(curNode==0){
curNode=que.size();
res.add(list);
list=new ArrayList<Integer>();
}
}
return res;
}
}

最新文章

  1. logstash VS splunk
  2. Rails中的缓存
  3. 【linux】vim编辑器vim+taglist+ctags的配置
  4. CentOS 修改线程数限制等(limits.conf)
  5. Another app is currently holding the yum lock; waiting for it to exit... 怎么解决
  6. 仿猪八戒一个提示(jQuery插件) v0.1 beta
  7. 电脑Win7如何取得文件管理所有权(提供各种GHOST版本的Windows)
  8. MiniProfiler使用点滴记录-2017年6月23日11:08:23
  9. Mysql内置的profiling性能分析工具
  10. 【转载】Linux下安装、配置、启动Apache
  11. WPF 控件之 Popup
  12. DJango 前三天小结
  13. Docker inside Docker 基于 Alpine Linux
  14. redis,nodejs,php,pub/sub 实战: 微信语音识别
  15. protobuf标准消息方法
  16. Debian 8 设置时区和时间配置
  17. mark CodeGenerator
  18. Ubuntu 14.04 更新gcc版本至4.9.2
  19. http报头 Accept 与 Content-Type 的区别
  20. windows下查看端口占用以及进程名称

热门文章

  1. CentOS中文乱码之解决办法
  2. BZOJ1566 【NOI2009】管道取珠
  3. Springboot框架中request.getInputStream()获取不到上传的文件流
  4. js中this 的四种用法
  5. 查看mysql连接情况,以及连接超时时间设置
  6. 洛谷 P4245 [模板]任意模数NTT —— 三模数NTT / 拆系数FFT(MTT)
  7. poj3613Cow Relays——k边最短路(矩阵快速幂)
  8. 如何用vs2013开发人员命令提示工具执行一个方法(一个简单的demo)
  9. ABI(Application Binary Interface)
  10. bzoj3836