标签:
1 public class Solution { 2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 3 List<List<Integer>> result = new ArrayList<List<Integer>>(); 4 if (root == null) { 5 return result; 6 } 7 Stack<TreeNode> stack = new Stack<TreeNode>(); 8 stack.push(root); 9 boolean flg = true; 10 while (!stack.isEmpty()) { 11 List<Integer> list = new ArrayList<Integer>(); 12 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 13 while (!stack.isEmpty()) { 14 TreeNode node = stack.pop(); 15 list.add(node.val); 16 if (flg) { 17 if (node.left != null) { 18 queue.offer(node.left); 19 } 20 if (node.right != null) { 21 queue.offer(node.right); 22 } 23 } else { 24 if (node.right != null) { 25 queue.offer(node.right); 26 } 27 if (node.left != null) { 28 queue.offer(node.left); 29 } 30 } 31 } 32 while (!queue.isEmpty()) { 33 stack.push(queue.poll()); 34 } 35 flg = !flg; 36 result.add(list); 37 } 38 return result; 39 } 40 }
下面的方法代码复杂度低一些
1 public class Solution { 2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 3 List<List<Integer>> result = new ArrayList<List<Integer>>(); 4 if (root == null) { 5 return result; 6 } 7 boolean flg = false; 8 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 9 queue.offer(root); 10 while (!queue.isEmpty()) { 11 List<Integer> list = new LinkedList<Integer>(); 12 int size = queue.size(); 13 for (int i = 0; i < size; i++) { 14 TreeNode node = queue.poll(); 15 if (flg) { 16 list.add(0, node.val); 17 } else { 18 list.add(node.val); 19 } 20 if (node.left != null) { 21 queue.offer(node.left); 22 } 23 if (node.right != null) { 24 queue.offer(node.right); 25 } 26 } 27 result.add(list); 28 flg = !flg; 29 } 30 return result; 31 } 32 }
[LeetCode]Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://www.cnblogs.com/vision-love-programming/p/5018362.html