mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0111.二叉树的最小深度.md
This commit is contained in:
@ -359,6 +359,39 @@ class Solution:
|
|||||||
return depth
|
return depth
|
||||||
```
|
```
|
||||||
|
|
||||||
|
迭代法:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 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 minDepth(self, root: TreeNode) -> int:
|
||||||
|
if not root:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
queue = collections.deque([(root, 1)])
|
||||||
|
|
||||||
|
while queue:
|
||||||
|
node, depth = queue.popleft()
|
||||||
|
|
||||||
|
# Check if the node is a leaf node
|
||||||
|
if not node.left and not node.right:
|
||||||
|
return depth
|
||||||
|
|
||||||
|
# Add left and right child to the queue
|
||||||
|
if node.left:
|
||||||
|
queue.append((node.left, depth+1))
|
||||||
|
if node.right:
|
||||||
|
queue.append((node.right, depth+1))
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
## Go
|
## Go
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user