当前位置:网站首页>【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;
}
}
边栏推荐
- 高数_复习_第4章:向量代数和空间解析几何
- 用PLSQL导出Oracle一个表
- Forbidden (CSRF token missing or incorrect.): /
- How to insist to use procedural system?
- 金仓数据库 KingbaseGIS 使用手册(6.2. 管理函数)
- 测试2年,当时身边一起入行的朋友已经月薪20k了,自己还没过万,到底差在了哪里?
- xlrd 与 xlsxwritter 的基本操作
- 2022-08-09 mysql/stonedb-子查询性能提升-概论
- (转)字符集编码标识符,数字表示字符编码
- 杭电多校-Counting Stickmen-(思维+组合数+容斥)
猜你喜欢
华为云全流程护航《流浪方舟》破竹首发,打造口碑爆款
迁移学习 & 凯明初始化
Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut
Qt message mechanism and events
SRv6性能测量
Mysql集群 ShardingSphere
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
kubesphere
干货!迈向鲁棒的测试时间适应
leetcode:331. 验证二叉树的前序序列化
随机推荐
国内BI厂商一览
H5实现分享功能
CGLIB源码易懂解析
【面试高频题】可逐步优化的链表高频题
带着昇腾去旅行:一日看尽金陵城里的AI胜景
70. 爬楼梯进阶版
异常处理(try,catch,finally)
Leetcode 236. 二叉树的最近公共祖先
【TS技术课堂】时间序列预测
Miscellaneous talk - the sorrow of programmers
2022/8/9 考试总结
PyQt5:入门使用教程
2022年最新《谷粒学院开发教程》:10 - 前台支付模块
tiup cluster template
Forbidden (CSRF token missing or incorrect.): /
力扣:518. 零钱兑换 II
为什么刀具数据库无法打开?
离散选择模型之Gumbel分布
DXF笔记:文字对齐的研究
Day 12 of learning to program