Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/ Secret
Created Jun 10, 2017

What would you like to do?
ZigZag level order travsersal
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
package com.interviewbytes.trees;
import java.util.*;
public class ZigZagLevelOrder {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
if (root != null) queue.offer(root);
boolean reverse = false;
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new ArrayList<>();
while (size > 0) {
TreeNode node = queue.poll();
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
if (reverse) Collections.reverse(level);
reverse = !reverse;
return list;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.