在树的广度遍历的时候,通常使用对列或者站来实现,大致思路为:先存储一行的数据,再记录每层的个数并不断地把下一层的数据存储到队列/栈中
相关题目:
二叉树的锯齿层次遍历
主要有两种思路
1、通过一个对列或者两个栈来实现,奇数层的时候,向对列的末尾先添加左孩子,再添加右孩子;当偶数层的时候,向队列的头先添加右孩子再添加左孩子
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
LinkedList<TreeNode> l=new LinkedList<>();
List<List<Integer>> res=new ArrayList<>();
if(root==null){
return new ArrayList<>();
}
l.add(root);
int i=1;
int index=1;
while(!l.isEmpty()){
List<Integer> item=new ArrayList<>();
int num=0;
if(i%2==1){
for(int j=1;j<=index;j++){
TreeNode t=l.pollFirst();
item.add(t.val);
if(t.left!=null){
l.add(t.left);
num++;
}
if(t.right!=null){
l.add(t.right);
num++;
}
}
} else {
for(int j=1;j<=index;j++){
TreeNode t2=l.pollLast();
item.add(t2.val);
if(t2.right!=null){
l.add(0,t2.right);
num++;
}
if(t2.left!=null){
l.add(0,t2.left);
num++;
}
}
}
i++;
index=num;
res.add(item);
}
return res;
}
}
2、正常的层序遍历输出,当为偶数层的时候,将输出的结果反转。
略(正常的层序遍历+链表反转)
于2020/10/13完成,动态更新