[leetCode]103. 二叉树的锯齿形层序遍历
程序员文章站
2022-05-20 23:12:52
...
题目
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
层序遍历 BFS
添加每一层的节点使用双端队列
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (root == null) return res;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean flag = false;
while (!queue.isEmpty()) {
int size = queue.size();
LinkedList<Integer> level = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
if(!flag) {
level.offerLast(cur.val);
} else {
level.offerFirst(cur.val);
}
if (cur.left != null)
queue.offer(cur.left);
if (cur.right != null)
queue.offer(cur.right);
}
res.add(level);
flag = !flag;
}
return res;
}
}