题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) { // write code here //也就是变羊的层序遍历 ArrayList<ArrayList<Integer>> ret = new ArrayList<>(); if(pRoot==null){ return ret; } Queue<TreeNode> q = new ArrayDeque<>(); q.add(pRoot); boolean f = true;//f==true 时从左到右t加入ret while(!q.isEmpty()){ ArrayList<Integer> t = new ArrayList<>(); int n = q.size(); for(int i =0;i<n;i++){ TreeNode cur = q.poll(); t.add(cur.val); //加入子节点入队列 if(cur.left!=null){ q.add(cur.left); } if(cur.right!=null){ q.add(cur.right); } } if(f){ ret.add(t); f = false; }else{ Collections.reverse(t); ret.add(t); f = true; } } return ret; } }