mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0104.二叉树的最大深度.md
This commit is contained in:
@ -419,26 +419,33 @@ class solution:
|
||||
return 1 + max(self.maxdepth(root.left), self.maxdepth(root.right))
|
||||
```
|
||||
|
||||
迭代法:
|
||||
层序遍历迭代法:
|
||||
```python
|
||||
import collections
|
||||
class solution:
|
||||
def maxdepth(self, root: treenode) -> int:
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def maxDepth(self, root: TreeNode) -> int:
|
||||
if not root:
|
||||
return 0
|
||||
depth = 0 #记录深度
|
||||
queue = collections.deque()
|
||||
queue.append(root)
|
||||
|
||||
depth = 0
|
||||
queue = collections.deque([root])
|
||||
|
||||
while queue:
|
||||
size = len(queue)
|
||||
depth += 1
|
||||
for i in range(size):
|
||||
for _ in range(len(queue)):
|
||||
node = queue.popleft()
|
||||
if node.left:
|
||||
queue.append(node.left)
|
||||
if node.right:
|
||||
queue.append(node.right)
|
||||
|
||||
return depth
|
||||
|
||||
```
|
||||
|
||||
### 559.n叉树的最大深度
|
||||
|
Reference in New Issue
Block a user