按照广度优先搜索套路,判断反向| #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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 { public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if (pRoot != null) { Deque<TreeNode> queue = new LinkedList<>(); queue.offer(pRoot); ArrayList<Integer> list = new ArrayList<>(); list.add(pRoot.val); res.add(list); boolean leftOrder = false; while (!queue.isEmpty()) { int size = queue.size(); ArrayList<Integer> temp = new ArrayList<>(); while (size > 0) { TreeNode poll = queue.poll(); if (poll.left != null) { queue.offer(poll.left); temp.add(poll.left.val); } if (poll.right != null) { queue.offer(poll.right); temp.add(poll.right.val); } size--; } if (temp.size()==0) { break; } if (!leftOrder) { Collections.reverse(temp); } res.add(temp); leftOrder = !leftOrder; } } return res; } }