难点:Z字形,奇数行从左向右输出,偶数行从右向左输出(但是注意这个偶数行的下一行又要以从左向右输出)。
解决思路:用栈和队列来解决顺序和逆序的问题。
1.用phase来表示奇数行还是偶数行;
2.对于奇数行用队列nodeQueue来记录所有点,对于偶数行,用nodeStack来记录所有点(从左到右push进去,则出来时从右到左),偶数行的输出用nodeStack弹出的值来完成;与nodeStack对应还有一个nodeQueueForSeq,用来记录偶数行的下一行的节点。
代码如下:
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> nodeLevels = new ArrayList<List<Integer>>();
if (root == null) return nodeLevels;
Stack<TreeNode> nodeStack = new Stack<TreeNode>(); // nodes output from right to left
Queue<TreeNode> nodeQueueForSeq = new LinkedList<TreeNode>(); //corresponding queue for nodeStack, because the next generation of this level should be from left to right
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); // nodes output from left to right
boolean phase = true; // true: from left to right; false: from right to left
TreeNode node = null;
TreeNode nodeForSeq = null;
nodeQueue.offer(root);
while(!nodeStack.empty() || nodeQueue.size() != 0){
List<Integer> nodeLevel = new ArrayList<Integer>();
if (phase == true){
while(nodeQueue.size() != 0){
node = nodeQueue.poll();
nodeLevel.add(node.val);
if (node.left != null) {
nodeStack.push(node.left);
nodeQueueForSeq.offer(node.left);
}
if (node.right != null) {
nodeStack.push(node.right);
nodeQueueForSeq.offer(node.right);
}
}
}else{
while(!nodeStack.empty()){
node = nodeStack.pop();
nodeLevel.add(node.val);
nodeForSeq = nodeQueueForSeq.poll();
if (nodeForSeq.left != null) nodeQueue.offer(nodeForSeq.left);
if (nodeForSeq.right != null) nodeQueue.offer(nodeForSeq.right);
//nodeLevel.add(nodeForValue.val);
}
}
nodeLevels.add(nodeLevel);
phase = !phase;
}
return nodeLevels;
}
}
解法二:找到一个更好更简单的方法(https://discuss.leetcode.com/topic/59174/1ms-short-java-solution-using-depth)
public class Solution {
// leftDirection = true means adding elements from left to right
void dfs(TreeNode root, List<List<Integer>> result, int depth, boolean leftDirection) {
if(root==null) return;
if(result.size()==depth){
result.add(new LinkedList<Integer>());
}
List<Integer> cur = result.get(depth);
if(!leftDirection) cur.add(0, root.val);
else cur.add(root.val);
dfs(root.left, result, depth+1, !leftDirection);
dfs(root.right, result, depth+1, !leftDirection);
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
dfs(root, result, 0, true);
return result;
}
}