title: '算法:按之字形顺序打印二叉树' cover: https://img.paulzzh.com/touhou/random?62 categories: 算法题目 toc: true date: 1996-07-27 08:00:00
<br/>
<!--more-->请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
题目很明显是要用栈做BFS, 关键是怎么BFS;
可以用两个栈分别用来遍历奇数行和偶数行;
这样对于奇数行从左到右遍历后, 偶数行出栈时自然是从右向左遍历, 以此类推;
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>(64);
if (pRoot == null) return res;
// 奇数层
Stack<TreeNode> stack1 = new Stack<>();
stack1.push(pRoot);
// 偶数层
Stack<TreeNode> stack2 = new Stack<>();
int level = 1;
while (!stack1.isEmpty() || !stack2.isEmpty()) {
ArrayList<Integer> layer = new ArrayList<>(64);
if ((level & 1) == 1) {
while (!stack1.isEmpty()) {
TreeNode pop = stack1.pop();
if (pop != null) {
layer.add(pop.val);
stack2.push(pop.left);
stack2.push(pop.right);
}
}
} else {
while (!stack2.isEmpty()) {
TreeNode pop = stack2.pop();
if (pop != null) {
layer.add(pop.val);
stack1.push(pop.right);
stack1.push(pop.left);
}
}
}
if (!layer.isEmpty()) {
level++;
res.add(layer);
}
}
return res;
}
}