-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathQue59.java
99 lines (63 loc) · 1.98 KB
/
Que59.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.ArrayList;
import java.util.Stack;
/**
* @author: hyl
* @date: 2019/08/18
**/
public class Que59 {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (pRoot == null){
return res;
}
Stack<TreeNode> s1 = new Stack<>();//s1表示奇数,从左到右输出
Stack<TreeNode> s2 = new Stack<>();//s2表示偶数,从右到左输出
int level = 1;
while (!s1.isEmpty() || !s2.isEmpty()){
ArrayList<Integer> list = new ArrayList<>();
if ((level & 1) == 1){
while (!s1.isEmpty()){
TreeNode node = s1.pop();
if (node != null){
list.add(node.val);
s2.push(node.left);
s2.push(node.right);
}
}
}else{
while (!s2.isEmpty()){
TreeNode node = s2.pop();
if (node != null){
list.add(node.val);
s1.push(node.right);
s1.push(node.left);
}
}
}
if (!list.isEmpty()){
res.add(list);
level++;
}
}
return res;
}
public static void main(String[] args) {
TreeNode node = new TreeNode(8);
node.left = new TreeNode(6);
node.right = new TreeNode(10);
node.left.left = new TreeNode(5);
node.left.right = new TreeNode(7);
node.right.left = new TreeNode(9);
node.right.right = new TreeNode(11);
//new Que59().Print(node);
assert (1 > 3);
}
}