43
43
44
44
<!-- 这里可写通用的实现逻辑 -->
45
45
46
- “BFS 层次遍历实现”。
46
+ ** 方法一:BFS**
47
+
48
+ 借助队列,逐层遍历。
49
+
50
+ 时间复杂度 O(n)。
51
+
52
+ ** 方法二:DFS**
53
+
54
+ 按深度遍历。
55
+
56
+ 假设当前深度为 i,遍历到的节点为 root。若结果列表 ` ans[i] ` 不存在,则创建一个空列表放入 ans 中,然后将 ` root.val ` 放入 ` ans[i] ` 。接着往下一层遍历(root 的子节点)。
57
+
58
+ 时间复杂度 O(n)。
47
59
48
60
<!-- tabs:start -->
49
61
50
62
### ** Python3**
51
63
52
64
<!-- 这里可写当前语言的特殊实现逻辑 -->
53
65
66
+ BFS:
67
+
54
68
``` python
55
69
"""
56
70
# Definition for a Node.
@@ -69,18 +83,47 @@ class Solution:
69
83
q = deque([root])
70
84
while q:
71
85
t = []
72
- for _ in range (len (q), 0 , - 1 ):
86
+ for _ in range (len (q)):
73
87
root = q.popleft()
74
88
t.append(root.val)
75
89
q.extend(root.children)
76
90
ans.append(t)
77
91
return ans
78
92
```
79
93
94
+ DFS:
95
+
96
+ ``` python
97
+ """
98
+ # Definition for a Node.
99
+ class Node:
100
+ def __init__(self, val=None, children=None):
101
+ self.val = val
102
+ self.children = children
103
+ """
104
+
105
+ class Solution :
106
+ def levelOrder (self , root : ' Node' ) -> List[List[int ]]:
107
+ def dfs (root , i ):
108
+ if root is None :
109
+ return
110
+ if len (ans) <= i:
111
+ ans.append([])
112
+ ans[i].append(root.val)
113
+ for child in root.children:
114
+ dfs(child, i + 1 )
115
+
116
+ ans = []
117
+ dfs(root, 0 )
118
+ return ans
119
+ ```
120
+
80
121
### ** Java**
81
122
82
123
<!-- 这里可写当前语言的特殊实现逻辑 -->
83
124
125
+ BFS:
126
+
84
127
``` java
85
128
/*
86
129
// Definition for a Node.
@@ -123,33 +166,54 @@ class Solution {
123
166
}
124
167
```
125
168
126
- 也可以使用 DFS:
169
+ DFS:
127
170
128
171
``` java
172
+ /*
173
+ // Definition for a Node.
174
+ class Node {
175
+ public int val;
176
+ public List<Node> children;
177
+
178
+ public Node() {}
179
+
180
+ public Node(int _val) {
181
+ val = _val;
182
+ }
183
+
184
+ public Node(int _val, List<Node> _children) {
185
+ val = _val;
186
+ children = _children;
187
+ }
188
+ };
189
+ */
190
+
129
191
class Solution {
130
192
public List<List<Integer > > levelOrder (Node root ) {
131
- List<List<Integer > > res = new ArrayList<> ();
132
- dfs(root, 0 , res );
133
- return res ;
193
+ List<List<Integer > > ans = new ArrayList<> ();
194
+ dfs(root, 0 , ans );
195
+ return ans ;
134
196
}
135
197
136
- private void dfs (Node root , int level , List<List<Integer > > res ) {
198
+ private void dfs (Node root , int i , List<List<Integer > > ans ) {
137
199
if (root == null ) {
138
200
return ;
139
201
}
140
- if (res . size() <= level ) {
141
- res . add(new ArrayList<> ());
202
+ if (ans . size() <= i ) {
203
+ ans . add(new ArrayList<> ());
142
204
}
143
- res . get(level ++ ). add(root. val);
205
+ ans . get(i ++ ). add(root. val);
144
206
for (Node child : root. children) {
145
- dfs(child, level, res );
207
+ dfs(child, i, ans );
146
208
}
147
209
}
148
210
}
149
211
```
150
212
151
213
### ** C++**
152
214
215
+ BFS:
216
+
153
217
``` cpp
154
218
/*
155
219
// Definition for a Node.
@@ -194,8 +258,50 @@ public:
194
258
};
195
259
```
196
260
261
+ DFS:
262
+
263
+ ```cpp
264
+ /*
265
+ // Definition for a Node.
266
+ class Node {
267
+ public:
268
+ int val;
269
+ vector<Node*> children;
270
+
271
+ Node() {}
272
+
273
+ Node(int _val) {
274
+ val = _val;
275
+ }
276
+
277
+ Node(int _val, vector<Node*> _children) {
278
+ val = _val;
279
+ children = _children;
280
+ }
281
+ };
282
+ */
283
+
284
+ class Solution {
285
+ public:
286
+ vector<vector<int>> levelOrder(Node* root) {
287
+ vector<vector<int>> ans;
288
+ dfs(root, 0, ans);
289
+ return ans;
290
+ }
291
+
292
+ void dfs(Node* root, int i, vector<vector<int>>& ans) {
293
+ if (!root) return;
294
+ if (ans.size() <= i) ans.push_back({});
295
+ ans[i++].push_back(root->val);
296
+ for (Node* child : root->children) dfs(child, i, ans);
297
+ }
298
+ };
299
+ ```
300
+
197
301
### ** Go**
198
302
303
+ BFS:
304
+
199
305
``` go
200
306
/* *
201
307
* Definition for a Node.
@@ -227,8 +333,41 @@ func levelOrder(root *Node) [][]int {
227
333
}
228
334
```
229
335
336
+ DFS:
337
+
338
+ ``` go
339
+ /* *
340
+ * Definition for a Node.
341
+ * type Node struct {
342
+ * Val int
343
+ * Children []*Node
344
+ * }
345
+ */
346
+
347
+ func levelOrder (root *Node ) [][]int {
348
+ var ans [][]int
349
+ var dfs func (root *Node, i int )
350
+ dfs = func (root *Node, i int ) {
351
+ if root == nil {
352
+ return
353
+ }
354
+ if len (ans) <= i {
355
+ ans = append (ans, []int {})
356
+ }
357
+ ans[i] = append (ans[i], root.Val )
358
+ for _ , child := range root.Children {
359
+ dfs (child, i+1 )
360
+ }
361
+ }
362
+ dfs (root, 0 )
363
+ return ans
364
+ }
365
+ ```
366
+
230
367
### ** TypeScript**
231
368
369
+ BFS:
370
+
232
371
``` ts
233
372
/**
234
373
* Definition for node.
@@ -262,6 +401,8 @@ function levelOrder(root: Node | null): number[][] {
262
401
}
263
402
```
264
403
404
+ DFS:
405
+
265
406
``` ts
266
407
/**
267
408
* Definition for node.
0 commit comments