题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
public class Solution { public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(new ArrayList<>()); if (pRoot == null) return res; Queue<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); TreeNode temp; boolean flag = false; // 隔行反转 while (!queue.isEmpty()) { ArrayList<Integer> arr = new ArrayList<>(); int len = queue.size(); for (int i = 0; i < len; i++) { temp = queue.poll(); arr.add(temp.val); if (temp.left != null) queue.add(temp.left); if (temp.right != null) queue.add(temp.right); } if (flag) Collections.reverse(arr); flag = !flag; res.add(arr); } return res; } }