mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +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))
|
return 1 + max(self.maxdepth(root.left), self.maxdepth(root.right))
|
||||||
```
|
```
|
||||||
|
|
||||||
迭代法:
|
层序遍历迭代法:
|
||||||
```python
|
```python
|
||||||
import collections
|
# Definition for a binary tree node.
|
||||||
class solution:
|
# class TreeNode:
|
||||||
def maxdepth(self, root: treenode) -> int:
|
# 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:
|
if not root:
|
||||||
return 0
|
return 0
|
||||||
depth = 0 #记录深度
|
|
||||||
queue = collections.deque()
|
depth = 0
|
||||||
queue.append(root)
|
queue = collections.deque([root])
|
||||||
|
|
||||||
while queue:
|
while queue:
|
||||||
size = len(queue)
|
|
||||||
depth += 1
|
depth += 1
|
||||||
for i in range(size):
|
for _ in range(len(queue)):
|
||||||
node = queue.popleft()
|
node = queue.popleft()
|
||||||
if node.left:
|
if node.left:
|
||||||
queue.append(node.left)
|
queue.append(node.left)
|
||||||
if node.right:
|
if node.right:
|
||||||
queue.append(node.right)
|
queue.append(node.right)
|
||||||
|
|
||||||
return depth
|
return depth
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 559.n叉树的最大深度
|
### 559.n叉树的最大深度
|
||||||
|
Reference in New Issue
Block a user