classSolution{ public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>(); //还是层次遍历 if(root==null){ return res; } Queue<TreeNode> queue = new LinkedList<>(); //root入队 queue.offer(root); //维护一个遍历,标识当前从左还是从右 int flag = 1;//1左-1右 while (!queue.isEmpty()){ List<Integer> list = new ArrayList<>(); int size = queue.size(); for(int i =0;i<size;i++){ TreeNode node = queue.poll();
//判断如何遍历 if(flag>0){ list.add(node.val);//这个结果每次加到之前的前面 }else{ list.add(0,node.val); } TreeNode left = node.left; TreeNode right = node.right; if(left!=null){ queue.offer(left); } if(right!=null){ queue.offer(right); } } flag *= -1; res.add(list); } return res; } }