按之字形顺序打印二叉树
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
常规的层序遍历解法:
import java.util.*; public class Solution { public ArrayList<ArrayList<Integer> > Print(TreeNode root) { ArrayList<ArrayList<Integer>> ret = new ArrayList<>(); if (root == null) return ret; Queue<TreeNode> queue = new LinkedList<>(); boolean rev = false; queue.offer(root); while(!queue.isEmpty()) { int len = queue.size(); ArrayList<Integer> list = new ArrayList<>(len); while((len--) > 0) { TreeNode cur = queue.poll(); if (rev) { list.add(0, cur.val); } else { list.add(cur.val); } if (cur.left != null) { queue.offer(cur.left); } if (cur.right != null) { queue.offer(cur.right); } } ret.add(list); rev = !rev; } return ret; } }