题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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) { /** 本题思路,即层序遍历 。需要倒叙的地方头插即可。 */ if(pRoot == null) return new ArrayList<>(); ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); //创建结果集合 Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(pRoot); int count = 0; //表示初始层数 while(!queue.isEmpty()){ ArrayList<Integer> list1 =new ArrayList<Integer>(); int size = queue.size(); while(size != 0){ size--; TreeNode node = queue.poll(); if(count%2 == 0) list1.add(node.val); else list1.add(0,node.val); if(node.left != null){ queue.add(node.left); } if(node.right != null){ queue.add(node.right); } } list.add(list1); count++; } return list; } }