Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 26, 2015 03:03
Show Gist options
  • Save dmnugent80/607095e8af7c875350c3 to your computer and use it in GitHub Desktop.
Save dmnugent80/607095e8af7c875350c3 to your computer and use it in GitHub Desktop.
Binary Tree Level Order Zig-Zag Traversal
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
LinkedList<Integer> list= new LinkedList<Integer>();
List<List<Integer>> listList= new ArrayList<List<Integer>>();
if (root == null) return listList;
Queue<TreeNode> treeQueue = new LinkedList<TreeNode>();
int countCurrentLevel = 1;
int countNextLevel = 0;
boolean goLeft = false;
treeQueue.add(root);
while (!treeQueue.isEmpty()){
TreeNode node = treeQueue.remove();
countCurrentLevel--;
if (goLeft){
list.addFirst(node.val);
if (node.left != null){
treeQueue.add(node.left);
countNextLevel++;
}
if (node.right != null){
treeQueue.add(node.right);
countNextLevel++;
}
}
else{
list.add(node.val);
if (node.left != null){
treeQueue.add(node.left);
countNextLevel++;
}
if (node.right != null){
treeQueue.add(node.right);
countNextLevel++;
}
}
if (countCurrentLevel == 0){
goLeft = (goLeft == true? false : true);
listList.add(list);
list = new LinkedList<Integer>();
countCurrentLevel = countNextLevel;
countNextLevel = 0;
}
}
return listList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment