@@ -281,6 +281,111 @@ class Solution {
281
281
282
282
Python:
283
283
284
+ 104.二叉树的最大深度
285
+ > 递归法:
286
+ ```python
287
+ class Solution :
288
+ def maxDepth(self, root: TreeNode) -> int:
289
+ return self.getDepth(root)
290
+
291
+ def getDepth(self, node):
292
+ if not node:
293
+ return 0
294
+ leftDepth = self.getDepth(node.left) #左
295
+ rightDepth = self.getDepth(node.right) #右
296
+ depth = 1 + max(leftDepth, rightDepth) #中
297
+ return depth
298
+ ```
299
+ > 递归法;精简代码
300
+ ```python
301
+ class Solution:
302
+ def maxDepth(self, root: TreeNode) -> int:
303
+ if not root:
304
+ return 0
305
+ return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
306
+ ```
307
+
308
+ > 迭代法:
309
+ ```python
310
+ import collections
311
+ class Solution :
312
+ def maxDepth(self, root: TreeNode) -> int:
313
+ if not root:
314
+ return 0
315
+ depth = 0 #记录深度
316
+ queue = collections.deque()
317
+ queue.append(root)
318
+ while queue:
319
+ size = len(queue)
320
+ depth += 1
321
+ for i in range(size):
322
+ node = queue.popleft()
323
+ if node.left:
324
+ queue.append(node.left)
325
+ if node.right:
326
+ queue.append(node.right)
327
+ return depth
328
+ ```
329
+
330
+ 559.N叉树的最大深度
331
+ > 递归法:
332
+ ```python
333
+ class Solution:
334
+ def maxDepth(self, root: 'Node') -> int:
335
+ if not root:
336
+ return 0
337
+ depth = 0
338
+ for i in range(len(root.children)):
339
+ depth = max(depth, self.maxDepth(root.children[i]))
340
+ return depth + 1
341
+ ```
342
+
343
+ > 迭代法:
344
+ ```python
345
+ import collections
346
+ class Solution :
347
+ def maxDepth(self, root: 'Node') -> int:
348
+ queue = collections.deque()
349
+ if root:
350
+ queue.append(root)
351
+ depth = 0 #记录深度
352
+ while queue:
353
+ size = len(queue)
354
+ depth += 1
355
+ for i in range(size):
356
+ node = queue.popleft()
357
+ for j in range(len(node.children)):
358
+ if node.children[ j] :
359
+ queue.append(node.children[ j] )
360
+ return depth
361
+ ```
362
+
363
+ > 使用栈来模拟后序遍历依然可以
364
+ ```python
365
+ class Solution:
366
+ def maxDepth(self, root: 'Node') -> int:
367
+ st = []
368
+ if root:
369
+ st.append(root)
370
+ depth = 0
371
+ result = 0
372
+ while st:
373
+ node = st.pop()
374
+ if node != None:
375
+ st.append(node) #中
376
+ st.append(None)
377
+ depth += 1
378
+ for i in range(len(node.children)): #处理孩子
379
+ if node.children[i]:
380
+ st.append(node.children[i])
381
+
382
+ else:
383
+ node = st.pop()
384
+ depth -= 1
385
+ result = max(result, depth)
386
+ return result
387
+ ```
388
+
284
389
285
390
Go:
286
391
0 commit comments