剑指offer之 从上往下打印二叉树
2024-08-28 16:29:14
import java.util.ArrayList;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null; public TreeNode(int val) {
this.val = val; } }
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
//定义一个辅助队列
LinkedList<TreeNode> queue=new LinkedList<>();
//存储一层的打印结果
ArrayList<Integer> resultCur=new ArrayList<Integer>();
if(root==null){
return resultCur;
}
//定义两个变量last和nlast,分别记录当前行的最右节点和下一行的最右节点
TreeNode last=root;
TreeNode nlast=root;
TreeNode cur=root;
queue.add(root);
while(queue.size()!=0){
cur=queue.poll();
resultCur.add(cur.val);
if(cur.left!=null){
queue.add(cur.left);
nlast=cur.left;
}
if(cur.right!=null){
queue.add(cur.right);
nlast=cur.right;
}
if(cur==last){
last=nlast;
}
}
return resultCur;
}
}
最新文章
- 关于本月第一天,本月最后一天的SQL代码
- 用自己赚的钱第一次坐飞机 那feel倍儿爽
- MATLAB-octave中3维向量场图的可视化
- Python 学习笔记(2) - 基本概念、运算符与表达式
- sql 语句左连接右连接小例子
- 返回表对象的方法之一--bulk collect into
- 浮点数运算的精度问题:以js语言为例
- 怎么样通过php使用html5实现多文件上传?(php多图上传)
- 关于 php 和 python 的浮点计算 0.1+0.2
- django -- Celery实现异步任务
- Django中简单添加HTML、css、js等文件(非正规添加,适合小白)
- SqlServer中的dbo是什么意思
- CentOS下用yum配置php+mysql+apache
- J2EE Oa项目上传服务器出现的乱码解决过程
- JavaScript for 循环累加 json 字符串
- select和epoll概念
- 【学习笔记】关于DOM4J:使用DOM4J解析XML文档
- 实现高可用-Keepalived
- Selenium2+python自动化41-绕过验证码(add_cookie)【转载】
- C++拷贝构造函数(深拷贝,浅拷贝)