LeetCode 103. 二叉树的锯齿形层序遍历
题目描述
思路分析
层序遍历
参考代码
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
35
36
37
38
39
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
var res [][]int
queue := []*TreeNode{root}
leftToRight := true
for len(queue) > 0 {
levelSize := len(queue)
level := make([]int, levelSize)
for i := 0; i < levelSize; i++ {
node := queue[0]
queue = queue[1:]
// 根据当前方向填充 level
if leftToRight {
level[i] = node.Val
} else {
level[levelSize-1-i] = node.Val
}
// 将子节点加入队列
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
res = append(res, level)
leftToRight = !leftToRight
}
return res
}
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
func zigzagLevelOrder(root *TreeNode) [][]int {
res := make([][]int, 0)
if root == nil {
return res
}
queue := []*TreeNode{root}
odd := false
for len(queue) > 0 {
level, size := make([]int, 0), len(queue)
for i := 0; i < size; i++ {
node := queue[0]
level = append(level, node.Val)
queue = queue[1:]
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
if odd {
for i, j := 0, len(level)-1; i < j; i, j = i+1, j-1 {
level[i], level[j] = level[j], level[i]
}
}
odd = !odd
res = append(res, level)
}
return res
}
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
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean odd = false;
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (odd) {
level.add(0, node.val);
} else {
level.add(node.val);
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
odd = !odd;
res.add(level);
}
return res;
}
}
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用