题目链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
题目如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
//在传统层次遍历的基础上,将每层得到的数据reverse下
/*Java 集合框架主要包括两种类型的容器,一种是集合(Collection),存储一个元素集合,另一种是图(Map),存储
键/值对映射。Collection 接口又有 3 种子类型,List、Set 和 Queue,再下面是一些抽象类,最后是具体实现类,常用
的有 ArrayList、LinkedList、HashSet、LinkedHashSet、HashMap、LinkedHashMap 等等。*/
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(root==null) return result;
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(root);
int flag=1;
while(!queue.isEmpty()){
int size=queue.size();
ArrayList<Integer> temp=new ArrayList<Integer>();
while(size--!=0){
TreeNode node=queue.poll();
temp.add(node.val);
if(node.left!=null) queue.offer(node.left);
if(node.right!=null) queue.offer(node.right);
}
flag=-flag;
if(flag==1) Collections.reverse(temp);//new and important
result.add(temp);
}
return result;
}
}