LeetCode 103. 二叉树的锯齿形层序遍历
程序员文章站
2022-05-21 08:16:18
...
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
BFS+双端队列
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> ans = new ArrayList<>();
if(root == null){
return ans;
}
queue.offer(root);
boolean isLeftToRight = true;
while(!queue.isEmpty()){
Deque<Integer> deque = new LinkedList<>();
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode cur = queue.poll();
if(isLeftToRight){
deque.offerLast(cur.val);
}else{
deque.offerFirst(cur.val);
}
if(cur.left != null){
queue.offer(cur.left);
}
if(cur.right != null){
queue.offer(cur.right);
}
}
isLeftToRight = !isLeftToRight;
ans.add(new ArrayList(deque));
}
return ans;
}
}