剑指Offer:二叉树打印成多行【23】
2024-10-19 16:38:30
剑指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;
}
}
最新文章
- 005.nginx配置文件
- CSS中有关水平居中和垂直居中的解决办法
- 关于js的keycode13
- JavaScript:关于事件处理程序何时可以直接访问元素的属性
- python特殊函数 __call__()
- hibernate date类型插入数据库时精度只到日期没有时间
- java模式之-模板方法模式
- Gradle多渠道打包[umeng]
- 洛谷 P1093 奖学金
- Leetcode 细节实现 Set Matrix Zeroes
- effective c++ 条款6 如果不想要就要告诉大家
- Ubuntu---regex
- linux学习记录.6.vscode调试c makefile
- Mishka and Divisors CodeForces - 703E
- SSH框架整合的其它方式
- [label][JavaScript]闭包阅读笔记
- 当有多个相同的DIV时,我怎么判断我点击的是哪个嘞
- The 15th UESTC Programming Contest Preliminary B - B0n0 Path cdoj1559
- vim的vim-addons的问题
- tess4j 注意事项
热门文章
- 【java】Map、Set、List不同数据结构的各种不同循环迭代的效率对比,使用场景
- 转: scala语言的简单入门 (IBM develop)
- Log4cplus入门
- [集合]解决system权限3389无法添加的用户情况
- Xshell 一款很养眼的配色方案推荐
- setTimeout()基础/setInterval()基础
- FileUpload控件预览图片
- 转 FreeBSD通过PORTS安装软件的几个常用命令
- linux init->;upstart->;systemd
- Asp.Net北大青鸟总结(四)-使用GridView实现真假分页