当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
matplotlib散点图自定义坐标轴(文字坐标轴)
33. Fabric通道、组织、节点、权限间关系
【JZOF】32从上往下打印二叉树
函数习题(下)
iNFTnews | 迪士尼如何布局Web3
What kind of mentality do you need to have when using the stock quantitative trading interface
高手这样看现货白银走势图
PyQt5:入门使用教程
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
6款跨境电商常用工具汇总
(转)字符集编码标识符,数字表示字符编码
力扣:377. 组合总和 Ⅳ
VR全景拍摄如何拍摄?如何使用拍摄器材?
JS--popstate事件--使用/教程/实例
集合运算样例
都在说云原生,那云原生到底是什么?
“我“是一名测试/开发程序员,小孙的内心独白......
如何知道电脑开机记录?
xlrd 与 xlsxwritter 的基本操作
使用股票量化交易接口需要具备怎么样的心态









