标签:practice pop 剑指offer 分析 ++ turn als sub view
import java.util.ArrayList; import java.util.LinkedList; import java.util.Iterator; /* 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>> list = new ArrayList<>(); if(null == pRoot){ return list; } //两个队列,raw主队列 LinkedList<TreeNode> raw = new LinkedList<TreeNode>(); raw.add(pRoot); boolean flag = true; while(raw.size()!=0){ //记录下当前行的大小 int size = raw.size(); ArrayList<Integer> tmp = new ArrayList<Integer>(); Iterator<TreeNode> iter = null; //flag=true 从左到右打印,false从右到左打印 if(flag){ iter = raw.iterator(); }else{ iter = raw.descendingIterator(); } //下一次方向相反 flag = !flag; while(iter.hasNext()){ tmp.add(iter.next().val); } list.add(tmp); //将下一行节点按从左到右记录到raw队列中 for(int i=0;i<size;i++){ TreeNode cur = raw.pop(); if(cur.left != null){ raw.add(cur.left); } if(cur.right != null){ raw.add(cur.right); } } } return list; } }
标签:practice pop 剑指offer 分析 ++ turn als sub view
原文地址:https://www.cnblogs.com/MoonBeautiful/p/13121665.html