LeetCode103.二叉树的锯齿形层序遍历
程序员文章站
2022-05-21 08:12:09
...
简单的层序遍历我简单的BFS~
/**
* 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) {
if(root == null) return new LinkedList<>();
//res 用来返回结果
List<List<Integer>> res = new LinkedList<>();
//队列 BFS
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
//sub 用来保存每一层的节点
List<Integer> sub = new LinkedList<>();
int leverCount = queue.size();
while(leverCount > 0){
TreeNode node = queue.poll();
//通过res的容量来判断层数
int n = res.size();
if(n % 2 == 0){
sub.add(node.val);
} else {
sub.add(0,node.val);
}
//BFS
if(node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
leverCount--;
}
res.add(sub);
}
return res;
}
}