-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution0103.java
More file actions
84 lines (76 loc) · 2.16 KB
/
Copy pathSolution0103.java
File metadata and controls
84 lines (76 loc) · 2.16 KB
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
81
82
83
84
// 103. 二叉树的锯齿形层序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
/*
“102.二叉树的层序遍历”,奇数层正序插入节点值,偶数层逆序插入节点值
*/
class Solution {
List<List<Integer>> list = new ArrayList<>();
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
dfs(root, 1);
return list;
}
public void dfs(TreeNode root, int layer) {
if (root == null) {
return;
}
if (list.size() < layer) {
list.add(new ArrayList<>());
}
if (layer % 2 == 1) {
list.get(layer - 1).add(root.val);
} else {
list.get(layer - 1).add(0, root.val);
}
dfs(root.left, layer + 1);
dfs(root.right, layer + 1);
}
}
/*
“102.二叉树的层序遍历”,加上是否反转标记,奇数层不变,偶数层反转子数组
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if (root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
boolean flag = false;
while (!queue.isEmpty()) {
int count = queue.size();
List<Integer> sonList = new ArrayList<>();
while (count > 0) {
TreeNode node = queue.remove();
sonList.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
count--;
}
if (flag) {
Collections.reverse(sonList);
}
list.add(sonList);
flag = !flag;
}
return list;
}
}