-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
45 lines (40 loc) · 1.34 KB
/
Solution.java
File metadata and controls
45 lines (40 loc) · 1.34 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (root == null)
return new ArrayList<List<Integer>>();
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> values = new ArrayList<Integer>();
LinkedList<TreeNode> stack = new LinkedList<TreeNode>(),
nextStack = new LinkedList<TreeNode>();
int direction = 1;
stack.add(root);
while (stack.size() > 0) {
TreeNode node = stack.poll();
if (direction == 1)
values.add(node.val);
else
values.add(0, node.val);
if (node.left != null)
nextStack.add(node.left);
if (node.right != null)
nextStack.add(node.right);
if (stack.size() == 0) {
direction = direction == 1 ? 0 : 1;
res.add(values);
values = new ArrayList<Integer>();
stack = nextStack;
nextStack = new LinkedList<TreeNode>();
}
}
return res;
}
}