标签:
标题: | Binary Tree Zigzag Level Order Traversal |
通过率: | 26.5% |
难度: | 中等 |
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
本题就是按层次遍历二叉树,每次遍历时进行queue的翻转即可。
具体看代码:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 12 List<List<Integer>> res = new ArrayList<List<Integer>>(); 13 if (root == null) { 14 return res; 15 } 16 List<Integer> tmp = new ArrayList<Integer>(); 17 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 18 queue.offer(root); 19 int num; 20 boolean reverse = false; 21 while (!queue.isEmpty()) { 22 num = queue.size(); 23 tmp.clear(); 24 for (int i = 0; i < num; i++) { 25 TreeNode node = queue.poll(); 26 tmp.add(node.val); 27 if (node.left != null) 28 queue.offer(node.left); 29 if (node.right != null) 30 queue.offer(node.right); 31 } 32 if (reverse) { 33 Collections.reverse(tmp); 34 reverse = false; 35 } 36 else 37 reverse = true; 38 res.add(new ArrayList<Integer>(tmp)); 39 } 40 return res; 41 42 } 43 }
leetcode------Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://www.cnblogs.com/pkuYang/p/4337453.html