import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList; /* 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<>(); //先建一个队列 Queue<TreeNode> queue = new LinkedList<>(); queue.offer(pRoot); boolean reserve = false; while(!queue.isEmpty()){ int size = queue.size(); ArrayList<Integer> innerList = new ArrayList<>(); for(int i = 0; i < size; i++){ TreeNode node = queue.poll(); if(node== null){ continue; } //判断插入的顺序 if(!reserve){ innerList.add(node.val); }else{ innerList.add(0,node.val); }
//按照正常的中序遍历,先左后右 queue.offer(node.left); queue.offer(node.right); } if(innerList.size()>0){ res.add(innerList); } //每内循环一次,就翻转一次标志位 reserve = !reserve; } return res; } }