当前位置:网站首页>32 JZOF 】 【 print down on binary tree
32 JZOF 】 【 print down on binary tree
2022-08-10 00:33:00 【sigh】
不分行从上往下打印出二叉树的每个节点,同层节点从左至右打印.例如输入{8,6,10,#,#,2,1},如以下图中的示例二叉树,则依次打印8,6,10,2,1(空节点不打印,跳过),请你将打印的结果存放到一个数组里面,返回.
by means of a queue.
import java.util.*;
import java.util.ArrayList;
/** 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) {
if (root == null) {
return new ArrayList<Integer>();
}
ArrayList<Integer> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
res.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return res;
}
}
边栏推荐
猜你喜欢
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
离散选择模型之Gumbel分布
金仓数据库 KingbaseGIS 使用手册(6.4. 几何对象存取函数)
Interfering with BGP routing---community attributes
DXF笔记:文字对齐的研究
OSG笔记:使用setFontResolution设置字体分辨率
EasyExcel使用
2022-08-09 mysql/stonedb-子查询性能提升-概论
YGG 经理人杯总决赛已圆满结束,来看看这份文字版总结!
高数_复习_第4章:向量代数和空间解析几何
随机推荐
带着昇腾去旅行:一日看尽金陵城里的AI胜景
VR全景拍摄如何拍摄?如何使用拍摄器材?
HBuilder X 不能运行到内置终端
异常处理(try,catch,finally)
JS中表单操作、addEventListener事件监听器
What is the stability of the quantitative trading interface system?
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
探索TiDB Lightning源码来解决发现的bug
shell数组
Filament-Material 绘制基本图形
集合运算样例
如何正则匹配乱码?
力扣:518. 零钱兑换 II
【Leetcode】2104. Sum of Subarray Ranges
What kind of mentality do you need to have when using the stock quantitative trading interface
信息系统项目管理师---第十一章项目风险管理历年考题
tiup cluster stop
完全背包理论
mysql中的key是怎么用的,或者这个值有什么意义,如下图?
伦敦银行情中短线的支撑和阻力位