题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://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 > Print(TreeNode pRoot) { ArrayList<ArrayList > ans = new ArrayList<>(); if(pRoot==null) return ans; Queue st = new LinkedList(); st.offer(pRoot); boolean flag=true; while(!st.isEmpty()){ int sz = st.size(); ArrayList temp = new ArrayList<>(); flag=!flag; for(int i=0;i<sz;i++){ TreeNode cur = st.poll(); temp.add(cur.val); if(cur.left!=null) st.offer(cur.left); if(cur.right!=null) st.offer(cur.right); } if(flag) Collections.reverse(temp); ans.add(temp); } return ans; }
}