给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
分析:很明显要二叉树的层序遍历,不同的是,要在层序遍历的基础上加一个开关,一会儿向左,一会儿向右,从而实现锯齿遍历,从后往前遍历的时候可以用双端队列来做,也可以将数组存到栈中再弹出来做。
参考代码:
public List> zigzagLevelOrder(TreeNode root) {
Queue
if(root==null) return new ArrayList<>();
queue.offer(root);
int sw=0;
List> ret = new ArrayList<>();
while(!queue.isEmpty()){
List
int size=queue.size();
Stack
while(size>0){
TreeNode tmp = queue.poll();
if(sw==0){
path.add(tmp.val);
}else{
s.push(tmp.val);
}
if(tmp.left!=null) queue.offer(tmp.left);
if(tmp.right!=null) queue.offer(tmp.right);
size—;
}
if(sw==1){
while(!s.isEmpty()){
path.add(s.pop());
}
sw=0;
}else{
sw=1;
}
ret.add(path);
}
return ret;
}
