题目描述:给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
解题思路:广度优先遍历
解法一:
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Queue<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
boolean isLeft = true;
while (!nodeQueue.isEmpty()) {
Deque<Integer> temp = new LinkedList<>();
int queueSize = nodeQueue.size();
for (int i = 0; i < queueSize; i++) {
TreeNode cur = nodeQueue.poll();
if (isLeft) {
temp.offerLast(cur.val);
} else {
temp.offerFirst(cur.val);
}
if (cur.left != null) {
nodeQueue.offer(cur.left);
}
if (cur.right != null) {
nodeQueue.offer(cur.right);
}
}
ans.add(new LinkedList<>(temp));
isLeft = !isLeft;
}
return ans;
}
}