简介
Java中双端队列Deque是一种数据结构,可以在其两端插入或删除元素,是队列与栈的结合。
leecode例题:
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
直接用双端队列实现起来就很方便:奇数行在双端队列的末尾添加元素,偶数行在双端队列的首部添加元素。
代码实现:
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result =new LinkedList<>();
if(root==null){
return result;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
int layer=1;//用来记录是奇数行还是偶数行
while(!queue.isEmpty()){
Deque<Integer> re=new LinkedList<>();
int curSize=queue.size();
for(int i=0;i<curSize;i++){
TreeNode cur=queue.poll();
if(cur.left!=null){
queue.add(cur.left);
}
if(cur.right!=null){
queue.add(cur.right);
}
if(layer%2==1){
re.addLast(cur.val);//奇数行从尾部添加
}else{
re.addFirst(cur.val);//偶数行从头部添加
}
}
layer++;
result.add(new LinkedList<>(re));//注意这里要进行一个转换
}
return result;
}
}