LeetCode 103 二叉树的锯齿形层序遍历
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (null == root) {
return result;
}
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
nodeQueue.offer(root);
Boolean isLeft = true;
while (!nodeQueue.isEmpty()) {
Deque<Integer> dequeue = new LinkedList<>();
Integer size = nodeQueue.size();
for (int i = 0; i < size; i++) {
TreeNode node = nodeQueue.poll();
if (isLeft) {
dequeue.offerLast(node.val);
} else {
dequeue.offerFirst(node.val);
}
if (null != node.left)
nodeQueue.offer(node.left);
if (null != node.right)
nodeQueue.offer(node.right);
}
result.add(new ArrayList<Integer>(dequeue));
isLeft = !isLeft;
}
return result;
}
}