当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
Analyses the development status quo of stock trading
Users should clearly know that quantitative trading is not a simple procedure
如何正则匹配乱码?
PyQt5: Getting Started Tutorial
深圳堡垒机厂家有哪些?重点推荐哪家?
浅析量股票化交易的发展现状
[Interface Test] Decoding the request body string of the requests library
tiup cluster stop
34. Fabric2.2 证书目录里各文件作用
JS--popstate事件--使用/教程/实例
金仓数据库 KingbaseGIS 使用手册(6.4. 几何对象存取函数)
全球不用交税的国家,为什么不交
CV复习:softmax代码实现
Day 12 of learning to program
金仓数据库 KingbaseGIS 使用手册(6.3. 几何对象创建函数)
力扣:279.完全平方数
守护进程
一体化伺服电机在三轴钻孔机中的应用
Qt message mechanism and events
kubesphere









