题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
方法:层次遍历,记录下每层节点,奇数层不变,偶数层翻转
import java.util.*; import java.util.ArrayList; /* 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(); Queue<TreeNode>queue=new LinkedList<>(); ArrayList<ArrayList<Integer>>result=new ArrayList<>(); queue.offer(pRoot); int curlevel=1; //层次遍历,入队 while(!queue.isEmpty()){ int size=queue.size(); ArrayList<Integer>temp=new ArrayList<>(); for(int i=0;i<size;i++){ TreeNode cur=queue.poll(); temp.add(cur.val); if(cur.left!=null)queue.offer(cur.left); if(cur.right!=null)queue.offer(cur.right); } //偶数层翻转 if(curlevel%2==0){ for(int i=0;i<size/2;i++){ int tmp=temp.get(i); temp.set(i,temp.get(size-1-i)); temp.set(size-1-i,tmp); } } curlevel++; result.add(temp); } return result; } }