给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
BFS+flag
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if(root==null){
return new ArrayList<List<Integer>>();
}
List<List<Integer>>res=new ArrayList<List<Integer>>();
// Deque<Integer>queue=new ArrayDeque<Integer>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
// queue.addLast(root);
queue.add(root);
boolean leftToRight = true;
while(queue.size()>0){
int size=queue.size();
ArrayList<Integer>temp=new ArrayList<Integer>();
for(int i=0;i<size;++i){
TreeNode t= queue.remove();
if(leftToRight){
temp.add(t.val);
}
else{
temp.add(0,t.val);
}
if(t.left!=null){
queue.add(t.left);
}
if(t.right!=null){
queue.add(t.right);
}
}
res.add(temp);leftToRight=!leftToRight;
}
return res;
}
}