-
Notifications
You must be signed in to change notification settings - Fork 1
/
Question32_III.java
80 lines (73 loc) · 2.09 KB
/
Question32_III.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.hncboy.swordreferstooffer;
import java.util.*;
/**
* @author hncboy
* @date 2021/10/7 10:04
* @description 剑指 Offer 32-III.从上到下打印二叉树 III
*
* 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
*
*
* 例如:
* 给定二叉树: [3,9,20,null,null,15,7],
*
* 3
* / \
* 9 20
* / \
* 15 7
* 返回其层次遍历结果:
*
* [
* [3],
* [20,9],
* [15,7]
* ]
*
* 提示:
* 节点总数 <= 1000
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Question32_III {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<TreeNode>() {{
add(root);
}};
while (!queue.isEmpty()) {
// 获取当前这层的数量
int currentSize = queue.size();
List<Integer> subList = new ArrayList<>(currentSize);
while (currentSize-- > 0) {
TreeNode node = queue.poll();
subList.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
// 通过奇偶的方式判断是否要逆序
if (result.size() % 2 == 1) {
Collections.reverse(subList);
}
result.add(subList);
}
return result;
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}