题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.ArrayList; import java.util.LinkedList; public class Solution { public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> list = new ArrayList<>(); if (pRoot == null) return list; LinkedList<TreeNode> queue = new LinkedList<>(); int levelflag = 1; queue.offer(pRoot); while (!queue.isEmpty()) { ArrayList<Integer> level = new ArrayList<>(); LinkedList<TreeNode> temp = new LinkedList<>(); temp.addAll(queue); int num = queue.size(); if (levelflag % 2 == 0) { for (int i = 0 ; i < num; i++) { TreeNode p = temp.getLast(); if (p.right != null) { queue.offer(p.right); } if (p.left != null) { queue.offer(p.left); } level.add(p.val); queue.remove(p); temp.removeLast(); } } else { for (int i = 0 ; i < num; i++) { TreeNode p = temp.getLast(); if (p.left != null) { queue.offer(p.left); } if (p.right != null) { queue.offer(p.right); } level.add(p.val); queue.remove(p); temp.removeLast(); } } list.add(level); levelflag++; } return list; } }