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). For example: Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
//“之”字型层序遍历,思想参考层序遍历的1与2就能想明白 //当此层不需要逆序时,使用thisLevelList.add(curNode.val) //当此层需要逆序时,使用thisLevelList.addFirst(curNode.val)来达到逆序的效果 //使用标志位zigzag来判断本层需要逆序否,初始root对应false(不需要逆序),每遍历完一层时改变zigzag的值 public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root==null) return result; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); nodeQueue.add(root); TreeNode nextLevelStarter; boolean zigzag = false; //第一层root不需要逆序 while(!nodeQueue.isEmpty()){ LinkedList<Integer> thisLevelList = new LinkedList<Integer>(); nextLevelStarter = null; while(nodeQueue.isEmpty()==false && nodeQueue.peek()!=nextLevelStarter){ TreeNode curNode = nodeQueue.remove(); if(!zigzag){ //与普通层序遍历的主要区别 thisLevelList.add(curNode.val); //不需要逆序 }else{ thisLevelList.addFirst(curNode.val); //需要逆序 } if(curNode.left!=null) nodeQueue.add(curNode.left); if(curNode.right!=null) nodeQueue.add(curNode.right); if(nextLevelStarter==null){ if(curNode.left!=null){ nextLevelStarter = curNode.left; }else if(curNode.right!=null){ nextLevelStarter = curNode.right; } } } zigzag = !zigzag; //当本层遍历完之后,修改标志位zigzag以下层使用 result.add(thisLevelList); } return result; } }