当前位置:网站首页>【JZOF】77按之字形打印二叉树
【JZOF】77按之字形打印二叉树
2022-08-09 22:11:00 【叹了口丶气】
题目描述:
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
解法:
- 第一种解法借助了JDK的Collections.reverse,将集合逆序。如果面试时候要求不许用这个工具类,则需要换一种写法。
public class LeftRightReverseOrder {
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
boolean reverse = false;
while (!queue.isEmpty()) {
ArrayList<Integer> list = new ArrayList<>();
int cnt = queue.size();
while (cnt-- > 0) {
TreeNode node = queue.poll();
if (node == null)
continue;
list.add(node.val);
queue.add(node.left);
queue.add(node.right);
}
if (reverse)
Collections.reverse(list);
reverse = !reverse;
if (list.size() != 0)
ret.add(list);
}
return ret;
}
}
- 第二种解法:
采用两个栈的方式来做。
stack1存放奇数层节点,奇数层节点的子节点按照左右的顺序push到stack2。
slack2存放偶数层节点。偶数层节点的子节点按照右左的顺序push到stack1。
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
if (pRoot == null) {
return res;
}
// 奇数层
Stack<TreeNode> s1 = new Stack<>();
// 偶数层
Stack<TreeNode> s2 = new Stack<>();
s1.push(pRoot);
while (!s1.isEmpty() || !s2.isEmpty()) {
ArrayList<Integer> row = new ArrayList<>();
if (!s1.isEmpty()) {
while (!s1.isEmpty()) {
TreeNode node = s1.pop();
row.add(node.val);
if (node.left != null) {
s2.push(node.left);
}
if (node.right != null) {
s2.push(node.right);
}
}
} else {
while (!s2.isEmpty()) {
TreeNode node = s2.pop();
row.add(node.val);
if (node.right != null) {
s1.push(node.right);
}
if (node.left != null) {
s1.push(node.left);
}
}
}
res.add(row);
}
return res;
}
}
边栏推荐
- 【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
- 高数_复习_第4章:向量代数和空间解析几何
- EasyExcel使用
- How to insist to use procedural system?
- 用PLSQL导出Oracle一个表
- 2022-08-09 mysql/stonedb-子查询性能提升-概论
- torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
- 中国SaaS企业排名,龙头企业Top10梳理
- leetcode:323. 无向图中连通分量的数目
- CV复习:softmax代码实现
猜你喜欢

【技术分享】SLA(服务等级协议)原理与配置

测试2年,当时身边一起入行的朋友已经月薪20k了,自己还没过万,到底差在了哪里?

ArrayList 和 LinkedList 区别

leetcode:323. 无向图中连通分量的数目

如何知道电脑开机记录?

Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut

月薪5K的运维小白如何成为月薪5W的高级架构师?

如何正则匹配乱码?

都在说云原生,那云原生到底是什么?

HBuilder X 不能运行到内置终端
随机推荐
leetcode:286.墙和门
ArrayList 和 LinkedList 区别
&& 不是此版本的有效语句分隔符
如何正则匹配乱码?
UNI-APP_ monitor page scroll h5 monitor page scroll
“我“是一名测试/开发程序员,小孙的内心独白......
正则表达式的实际使用
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
shell array
用PLSQL导出Oracle一个表
全面解析FPGA基础知识
OSS文件上传
2022-08-09 mysql/stonedb-慢SQL-Q16分析
34. Fabric2.2 证书目录里各文件作用
【实用工具系列】MathCAD入门安装及快速上手使用教程
新增一地公布2022下半年软考报考时间
JS中表单操作、addEventListener事件监听器
【AtomicInteger】常规用法
tiup cluster template
daemon