借助队列层序遍历二叉树,根据当前遍历到的层数,决定是否将当前层元素倒序,初始化根节点所在层layer = 1,奇数层从左到右的遍历,偶数层从右向左遍历,因此当我们遍历完当前层的所有元素,并且得到一个curLayer的列表,列表中存储了所有从左向右遍历得到的值,如果是偶数层,就需要把当前列表中的元素逆序输出,通过调用Collections.reverse(curLayer)方法实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int layer = 1;
//奇数层 从左向右 偶数层 从右向左
while (!queue.isEmpty()) {
int sz = queue.size();
List<Integer> curLayer = new ArrayList<>();
for (int i = 0; i < sz; i++) {
TreeNode cur = queue.poll();
curLayer.add(cur.val);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
if (layer % 2 == 0) {
Collections.reverse(curLayer);
}
res.add(curLayer);
layer += 1;
}
return res;
}
}