文章524
标签277
分类67

算法:按之字形顺序打印二叉树


按之字形顺序打印二叉树

按之字形顺序打印二叉树

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。


分析

题目很明显是要用栈做BFS, 关键是怎么BFS;

可以用两个栈分别用来遍历奇数行和偶数行;

这样对于奇数行从左到右遍历后, 偶数行出栈时自然是从右向左遍历, 以此类推;


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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;
}
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/cn/1996/07/27/%E7%AE%97%E6%B3%95-%E6%8C%89%E4%B9%8B%E5%AD%97%E5%BD%A2%E9%A1%BA%E5%BA%8F%E6%89%93%E5%8D%B0%E4%BA%8C%E5%8F%89%E6%A0%91/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可