剑指Offer:二叉树打印成多行【23】

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

题目分析

  

Java题解

package tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue; public class PrintByLevel {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
t1.left=t2;
t1.right=t3;
t2.left=t4;
t2.right=t5;
}
static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> re = new ArrayList<>();
if (pRoot==null)
return re; Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
int nextLevel =0;
int toBePrinted = 1;
ArrayList<Integer> cuLevel = new ArrayList<>(); while (!queue.isEmpty())
{
TreeNode tmp = queue.poll();
cuLevel.add(tmp.val);
if(tmp.left!=null)
{
queue.add(tmp.left);
nextLevel++;
}
if(tmp.right!=null)
{
queue.add(tmp.right);
nextLevel++;
}
toBePrinted--;
if(toBePrinted==0)
{
re.add(cuLevel);
cuLevel = new ArrayList<>();
toBePrinted = nextLevel;
nextLevel=0;
} }
return re;
}
}

  

最新文章

  1. 005.nginx配置文件
  2. CSS中有关水平居中和垂直居中的解决办法
  3. 关于js的keycode13
  4. JavaScript:关于事件处理程序何时可以直接访问元素的属性
  5. python特殊函数 __call__()
  6. hibernate date类型插入数据库时精度只到日期没有时间
  7. java模式之-模板方法模式
  8. Gradle多渠道打包[umeng]
  9. 洛谷 P1093 奖学金
  10. Leetcode 细节实现 Set Matrix Zeroes
  11. effective c++ 条款6 如果不想要就要告诉大家
  12. Ubuntu---regex
  13. linux学习记录.6.vscode调试c makefile
  14. Mishka and Divisors CodeForces - 703E
  15. SSH框架整合的其它方式
  16. [label][JavaScript]闭包阅读笔记
  17. 当有多个相同的DIV时,我怎么判断我点击的是哪个嘞
  18. The 15th UESTC Programming Contest Preliminary B - B0n0 Path cdoj1559
  19. vim的vim-addons的问题
  20. tess4j 注意事项

热门文章

  1. 【java】Map、Set、List不同数据结构的各种不同循环迭代的效率对比,使用场景
  2. 转: scala语言的简单入门 (IBM develop)
  3. Log4cplus入门
  4. [集合]解决system权限3389无法添加的用户情况
  5. Xshell 一款很养眼的配色方案推荐
  6. setTimeout()基础/setInterval()基础
  7. FileUpload控件预览图片
  8. 转 FreeBSD通过PORTS安装软件的几个常用命令
  9. linux init-&gt;upstart-&gt;systemd
  10. Asp.Net北大青鸟总结(四)-使用GridView实现真假分页