-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
50 lines (50 loc) · 1.66 KB
/
Solution.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<TreeNode>> answerList = new ArrayList<List<TreeNode>>();
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (root == null) {
return list;
}
List<TreeNode> initList = new ArrayList<TreeNode>();
initList.add(root);
answerList.add(initList);
for (int i = 0; i < answerList.size(); i++) {
System.out.println("i=" + i);
List<Integer> l = new ArrayList<Integer>();
List<TreeNode> newList = new ArrayList<TreeNode>();
for (int j = answerList.get(i).size() - 1; j >= 0; j--) {
TreeNode tree = answerList.get(i).get(j);
l.add(answerList.get(i).get(j).val);
if (i % 2 == 1) {
if (tree.right != null) {
newList.add(tree.right);
}
if (tree.left != null) {
newList.add(tree.left);
}
} else {
if (tree.left != null) {
newList.add(tree.left);
}
if (tree.right != null) {
newList.add(tree.right);
}
}
}
list.add(l);
if (newList.size() != 0) {
answerList.add(newList);
}
}
return list;
}
}