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).
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] ]
1.和I一样,只不过加里面的那个List的时候用一下.add(0, item)。就倒序了。
2.用stack替代queue。不过要注意a)不同方向层处理时先加左节点还是先加右节点不一样的。b)每层产生下层的stack的时候要new stack,避免同一个stack内又加又减混乱了。queue因为拿头部,所以只要size取出来定好就解决了,stack取尾部,size定好还不够,就不能允许你再拿刚加进去的东西了。
1实现:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: A Tree * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values. */ public List<List<Integer>> zigzagLevelOrder(TreeNode root) { // write your code here List<List<Integer>> result = new ArrayList<List<Integer>>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); if (root == null) { return result; } boolean isForward = true; queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); List<Integer> level = new ArrayList<Integer>(); // !!! for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (isForward) { level.add(node.val); } else { level.add(0,node.val); } if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } result.add(level); // !!! isForward = !isForward; } return result; } }
2实现:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: A Tree * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values. */ public List<List<Integer>> zigzagLevelOrder(TreeNode root) { // write your code here List<List<Integer>> result = new ArrayList<List<Integer>>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if (root == null) { return result; } boolean isForward = true; stack.push(root); while (!stack.isEmpty()) { int size = stack.size(); List<Integer> level = new ArrayList<Integer>(); // !!! Stack<TreeNode> newStack = new Stack<TreeNode>(); for (int i = 0; i < size; i++) { TreeNode node = stack.pop(); level.add(node.val); if (isForward) { if (node.left != null) { newStack.push(node.left); } if (node.right != null) { newStack.push(node.right); } } else { if (node.right != null) { newStack.push(node.right); } if (node.left != null) { newStack.push(node.left); } } } result.add(level); // !!! isForward = !isForward; stack = newStack; } return result; } }