题目链接:按之字型顺序打印二叉树
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> Print (TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int i = 1;
while(q.size() > 0)
{
ArrayList<Integer> lev = new ArrayList<>();
int len = q.size();
for(int j = 0; j < len; j ++)
{
TreeNode t = q.peek();
q.poll();
lev.add(t.val);
if(t.left != null) q.offer(t.left);
if(t.right != null) q.offer(t.right);
}
if(i % 2 == 0) Collections.reverse(lev);
res.add(lev);
i ++;
}
return res;
}
}