103.二叉树的锯齿形层序遍历
方法:广度优先搜索
/**
* 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) {
//利用广度优先搜索
List<List<Integer>> ans = new LinkedList<List<Integer>>();
if(root == null){
return ans;
}
Queue<TreeNode> queue = new LinkedList<>(); //定义一个队列
queue.offer(root);
boolean isLeft = true;
while(!queue.isEmpty()){
Deque<Integer> levelList = new LinkedList<>();
int size = queue.size();
for(int i = 0 ;i < size;i++){
TreeNode curNode = queue.poll();
if(isLeft){
levelList.offerLast(curNode.val);
}else{
levelList.offerFirst(curNode.val);
}
if(curNode.left!=null){
queue.offer(curNode.left);
}
if(curNode.right!=null){
queue.offer(curNode.right);
}
}
ans.add(new LinkedList<Integer>(levelList));
isLeft = !isLeft;
}
return ans;
}
}