Repository navigation
Expand file tree
/
Copy pathBinaryTreeZigZag.java
More file actions
57 lines (55 loc) · 1.78 KB
/
Copy pathBinaryTreeZigZag.java
File metadata and controls
57 lines (55 loc) · 1.78 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
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreeZigZag {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null)
return result;
Stack<TreeNode> st = new Stack<TreeNode>();
boolean isRight = true;
st.push(root);
List<Integer> first = new LinkedList<Integer>();
first.add(root.val);
result.add(first);
while (!st.isEmpty()) {
Stack<TreeNode> temp = new Stack<TreeNode>();
List<Integer> list = new LinkedList<Integer>();
while (!st.isEmpty()) {
TreeNode cur = st.pop();
if (isRight) {
if (cur.right != null) {
temp.push(cur.right);
list.add(cur.right.val);
}
if (cur.left != null) {
temp.push(cur.left);
list.add(cur.left.val);
}
} else {
if (cur.left != null) {
temp.push(cur.left);
list.add(cur.left.val);
}
if (cur.right != null) {
temp.push(cur.right);
list.add(cur.right.val);
}
}
}
if (!list.isEmpty())
result.add(list);
st = temp;
temp = null;
list = null;
isRight = (isRight) ? false : true;
}
return result;
}
}