Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */
publicclassSolution { /** * @param root: The root of binary tree. * @return: A list of lists of integer include * the zigzag level order traversal of its nodes' values */ public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> result = newArrayList<ArrayList<Integer>>(); if (root == null) return result;
booleanodd=true; Queue<TreeNode> q = newLinkedList<TreeNode>(); q.offer(root); while (!q.isEmpty()) { // level traversal intqLen= q.size(); ArrayList<Integer> level = newArrayList<Integer>(); for (inti=0; i < qLen; i++) { TreeNodenode= q.poll(); level.add(node.val); if (node.left != null) q.offer(node.left); if (node.right != null) q.offer(node.right); } // add level order reverse for even if (odd) { result.add(level); } else { Collections.reverse(level); result.add(level); } // flip odd and even odd = !odd; }