LeetCode/103. 二叉树的锯齿形层次遍历

103. 二叉树的锯齿形层次遍历

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

示例:
给定二叉树 [3,9,20,null,null,15,7],

        3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

1
2
3
4
5
[
[3],
[20,9],
[15,7]
]

来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题解:

本题还是基于层序遍历的框架,题目所说的锯齿遍历,就是一行是正序,一行是反序,这种情况设置一个count变量,来隔行判断本行应该正序还是反序存储。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int count = 0;

while (!queue.isEmpty()) {
LinkedList<Integer> temp = new LinkedList<>();
int len = queue.size();
for (int i = 0; i < len; i++) {
TreeNode node = queue.poll();
if (count % 2 != 0) {
//头插元素,即逆序
temp.add(0, node.val);
} else {
temp.add(node.val);
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
count++;
result.add(temp);
}
return result;
}
}

Comments