103. Binary Tree Zigzag Level Order Traversal
阿新 • • 發佈:2017-06-06
itl eve lean cnblogs lee empty for evel ive
題目:
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
鏈接: http://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
6/5/2017
2ms, 42%
註意的問題:
1. 第8行leftToRight左右的方向順序
2. LinkedList addFirst, addLast
1 public class Solution { 2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 3 List<List<Integer>> ret = newArrayList<>(); 4 if (root == null) return ret; 5 6 LinkedList<TreeNode> list = new LinkedList<TreeNode>(); 7 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 8 boolean leftToRight = true; 9 queue.add(root); 10 11while (!queue.isEmpty()) { 12 int size = queue.size(); 13 List<Integer> temp = new ArrayList<Integer>(); 14 15 for (int i = 0; i < size; i++) { 16 TreeNode node = queue.poll(); 17 if (leftToRight) { 18 if (node.left != null) { 19 list.addFirst(node.left); 20 } 21 if (node.right != null) { 22 list.addFirst(node.right); 23 } 24 } else { 25 if (node.right != null) { 26 list.addFirst(node.right); 27 } 28 if (node.left != null) { 29 list.addFirst(node.left); 30 } 31 } 32 temp.add(node.val); 33 } 34 ret.add(temp); 35 int listSize = list.size(); 36 for (int i = 0; i < listSize; i++) { 37 queue.add(list.poll()); 38 } 39 leftToRight = !leftToRight; 40 } 41 return ret; 42 } 43 }
更多討論
https://discuss.leetcode.com/category/111/binary-tree-zigzag-level-order-traversal
103. Binary Tree Zigzag Level Order Traversal