[leetcode]103. Binary Tree Zigzag Level Order Traversal二叉樹來回遍歷
阿新 • • 發佈:2018-11-08
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] ]
題目
思路
1. use Queue to help BFS
2. once scan current level, make a U-turn, then scan next level
程式碼
1 class Solution { 2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 3 List<List<Integer>> result = newArrayList<>(); 4 Queue<TreeNode> queue = new LinkedList<>(); 5 queue.add(root); 6 int level = 0; 7 // lever order traversal 8 while (!queue.isEmpty()) { 9 int size = queue.size(); 10 List<Integer> list = new ArrayList<>();11 for (int i = 0; i < size; i++) { 12 TreeNode node = queue.remove(); 13 if (node != null) { 14 list.add(node.val);8 15 queue.add(node.left); 16 queue.add(node.right); 17 } 18 } 19 if (!list.isEmpty()) { 20 // make a U-turn 21 if (level % 2 == 1) { 22 Collections.reverse(list); 23 } 24 result.add(list); 25 } 26 level++; 27 } 28 return result; 29 } 30 }