剑指Offer_59

题目

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

解题思路

解法一:

简洁版本,在数据大的时候效率并不高,因为偶数层的AarrayList总是操作Collections.revers(A)

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
46
47
48
49
50
51
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Collections;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> AA = new ArrayList<>();
if(pRoot == null){
return AA;
}
LinkedList<TreeNode> nodeList = new LinkedList<>();
nodeList.add(pRoot);
boolean isEven = false;
while(!nodeList.isEmpty()){
ArrayList<Integer> A = new ArrayList<>();
//这里的size要保存,nodeList的size是动态的
int size = nodeList.size();
for(int i = 0; i < size; ++i){
TreeNode node = nodeList.removeFirst();
A. add(node.val);
if(node.left != null){
nodeList.add(node.left);
}
if(node.right != null){
nodeList.add(node.right);
}
}
//偶数层的元素逆序
if(isEven){
Collections.reverse(A);
}
isEven = !isEven;
AA.add(A);
}
return AA;
}
}

解法二:

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.ArrayList;
import java.util.LinkedList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> AA = new ArrayList<>();
if (pRoot == null) {
return AA;
}
LinkedList<TreeNode> oddList = new LinkedList<>();
LinkedList<TreeNode> evenList = new LinkedList<>();
oddList.add(pRoot);
boolean isEven = false;
while(!oddList.isEmpty() || !evenList.isEmpty()){
ArrayList<Integer> A = new ArrayList<>();
if(isEven){
while (!evenList.isEmpty()){
TreeNode node = evenList.removeFirst();
A.add(node.val);
if(node.right != null){
oddList.addFirst(node.right);
}
if(node.left != null){
oddList.addFirst(node.left);
}
}
}
else{
while(!oddList.isEmpty()){
TreeNode node = oddList.removeFirst();
A.add(node.val);
if(node.left != null){
evenList.addFirst(node.left);
}
if(node.right != null){
evenList.addFirst(node.right);
}
}
}
isEven = !isEven;
AA.add(A);
}
return AA;
}
}