题目链接
法一
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
List<Integer> level = new LinkedList<>();
int levelSize = q.size();
while (levelSize > 0) {
TreeNode now = q.poll();
if (ans.size() % 2 == 0) {
level.add(now.val);
} else {
level.add(0, now.val);
}
if (now.left != null) {
q.offer(now.left);
}
if (now.right != null) {
q.offer(now.right);
}
levelSize--;
}
ans.add(level);
}
return ans;
}
法二(快)
public List<List<Integer>> zigzagLevelOrder_2(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
boolean flag = true;
while (!q.isEmpty()) {
int levelSize = q.size();
Integer[] level = new Integer[levelSize];
while (levelSize > 0) {
TreeNode now = q.poll();
level[flag ? level.length - levelSize : levelSize - 1] = now.val;
if (now.left != null) {
q.offer(now.left);
}
if (now.right != null) {
q.offer(now.right);
}
levelSize--;
}
flag = !flag;
ans.add(Arrays.asList(level));
}
return ans;
}
本地测试
lay.showTitle(103);
Solution103 sol103 = new Solution103();
List<Integer> arr103 = Arrays.asList(3, 9, 20, null, null, 15, 7);
TreeNode root103 = treeOpt.createTreeByLayerOrder(arr103);
treeOpt.layerOrder(root103);
List<List<Integer>> ans103_1 = sol103.zigzagLevelOrder(root103);
arrayOpt.showIntLists(ans103_1);
System.out.println();
List<List<Integer>> ans103_2 = sol103.zigzagLevelOrder_2(root103);
arrayOpt.showIntLists(ans103_2);