103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
分析:用一个flag来表示存入list的方向即可。
1 public class Solution { 2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 3 List<List<Integer>> allLists = new ArrayList<>(); 4 if (root == null) return allLists; 5 6 List<Integer> temp = new LinkedList<>(); 7 Queue<TreeNode> queue = new LinkedList<>(); 8 9 queue.offer(root); 10 int direction = 1; 11 12 while(!queue.isEmpty()) { 13 int size = queue.size(); 14 15 for (int i = 0; i < size; i++) { 16 TreeNode node = queue.poll(); 17 if (direction == 1) { 18 temp.add(node.val); 19 } else { 20 temp.add(0, node.val); 21 } 22 if (node.left != null) queue.offer(node.left); 23 if (node.right != null) queue.offer(node.right); 24 } 25 allLists.add(new LinkedList<Integer>(temp)); 26 temp.clear(); 27 direction *= -1; 28 } 29 return allLists; 30 } 31 }

浙公网安备 33010602011771号