利用双向队列
偶数层当栈用,
奇数层当队列用
class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Deque<TreeNode> dp = new LinkedList<>(); if(root == null) return res; dp.addFirst(root); boolean flag = true; while(!dp.isEmpty()){ int size = dp.size(); List<Integer> level = new ArrayList<>(); for(int i=0; i<size; i++){ if(flag){ TreeNode cur = dp.removeFirst(); System.out.println(cur.val); if(cur.left != null) dp.addLast(cur.left); if(cur.right != null) dp.addLast(cur.right); level.add(cur.val); }else{ TreeNode cur = dp.removeLast(); if(cur.right != null) dp.addFirst(cur.right); if(cur.left != null) dp.addFirst(cur.left); level.add(cur.val); } } if(!level.isEmpty()) res.add(level); flag = !flag; } return res; } }