题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
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 pRoot) { // write code here if (pRoot == null) { return new ArrayList<>(); } Queue<TreeNode> que = new LinkedList<>(); ArrayList<ArrayList<Integer>> res = new ArrayList<>(); boolean flag = false; que.add(pRoot); while (!que.isEmpty()) { int size = que.size(); ArrayList<Integer> tmp = new ArrayList<>(); for (int i = 0; i < size; i++) { TreeNode t = que.remove(); tmp.add(t.val); if (t.left != null) { que.add(t.left); } if (t.right != null) { que.add(t.right); } } if (flag == true) Collections.reverse(tmp); flag = !flag; res.add(tmp); } return res; } }