-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryTreeZigzagLevelOrderTraversal.java
More file actions
46 lines (38 loc) · 1.22 KB
/
BinaryTreeZigzagLevelOrderTraversal.java
File metadata and controls
46 lines (38 loc) · 1.22 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
package com.company;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class BinaryTreeZigzagLevelOrderTraversal {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> mList = new ArrayList<>();
if (root == null) return mList;
helper(mList, root, 0);
return mList;
}
public void helper(List<List<Integer>> mList, TreeNode root, int height) {
if (height >= mList.size()) mList.add(new LinkedList<>());
if (height % 2 == 0) {
mList.get(height).add(0, root.val);
} else {
mList.get(height).add(root.val);
}
if (root.right != null) helper(mList, root.right, height + 1);
if (root.left != null) helper(mList, root.left, height + 1);
}
@Test
public void test() {
List<Integer> mList = new LinkedList<>();
mList.add(5);
mList.add(0, 6);
for (Integer a : mList) System.out.print(a + " ");
}
}