# My easy to understand accepted JAVA solution

• My basic idea is to loop the tree level by level, and zigzag is achieved by alternately scanning the next level from left to right and from right to left. Super easy to understand:-) Time Complexity is O(N).

``````public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> toReturn = new LinkedList<List<Integer>>();
List<Integer> level = new LinkedList<Integer>();

List<TreeNode> treeLevel = new LinkedList<TreeNode>();
List<List<TreeNode>> treeLevels = new LinkedList<List<TreeNode>>();

if(root == null){
}

//initializing first level
int prelevelIndex = 0;

while(!treeLevel.isEmpty()){
level = new LinkedList<Integer>();
treeLevel = new LinkedList<TreeNode>();
//loop through the previous level
for (int i = treeLevels.get(prelevelIndex).size() - 1; i >= 0; i--) {
TreeNode t = treeLevels.get(prelevelIndex).get(i);
if (prelevelIndex % 2 == 0) { // scan the next level from right to left
if (t.right != null) {
}
if (t.left != null) {
}
} else { //zigzag is achieved by alternate scan the next level from left to right.
if (t.left != null) {
}
if (t.right != null) {
}
}
}
//initializing next level
if(!treeLevel.isEmpty()){
prelevelIndex++;