题目: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,null,null,15,7],
就是说,第一层从左到右,第二层从右到左,依次下去
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
层次遍历的变种,每次判断下flag
每遍历一次,flag = -flag;
将一层的所有元素放到栈里面,清空List
再从栈里面取出,放到List
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> listAll = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
int flag = -1;
if(root == null) {
return listAll;
}
queue.offer(root);
while(!queue.isEmpty()) {//前面的就是普通的层次遍历
int levelSize = queue.size();
List<Integer> listLevel = new ArrayList<>();
for(int i = 0; i < levelSize; i++) {
if(queue.peek().left != null) {
queue.offer(queue.peek().left);
}
if(queue.peek().right != null) {
queue.offer(queue.peek().right);
}
listLevel.add(queue.poll().val);
}
Stack<Integer> stack = new Stack<>();
if(flag == 1) {//这里判断是否要反向遍历
for(Integer i : listLevel) {
stack.push(i);//从list中放入stack
}
listLevel.clear();//清空list
while(!stack.isEmpty()) {
listLevel.add(stack.pop());//依次从栈中取出
}
}
flag = -flag;
listAll.add(listLevel);
}
return listAll;
}
}