Update 0111.二叉树的最小深度.md

This commit is contained in:
jianghongcheng
2023-05-04 00:23:53 -05:00
committed by GitHub
parent 1b1b51750d
commit 75d137eb1c

View File

@ -300,44 +300,63 @@ class Solution {
递归法: 递归法:
```python ```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: class Solution:
def minDepth(self, root: TreeNode) -> int: def minDepth(self, root: TreeNode) -> int:
if not root: if not root:
return 0 return 0
if not root.left and not root.right: if not root.left and not root.right:
return 1 return 1
min_depth = 10**9 left_depth = float('inf')
right_depth = float('inf')
if root.left: if root.left:
min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度 left_depth = self.minDepth(root.left)
if root.right: if root.right:
min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度 right_depth = self.minDepth(root.right)
return min_depth + 1
return 1 + min(left_depth, right_depth)
``` ```
迭代法: 迭代法:
```python ```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: class Solution:
def minDepth(self, root: TreeNode) -> int: def minDepth(self, root: TreeNode) -> int:
if not root: if not root:
return 0 return 0
que = deque() depth = 0
que.append(root) queue = collections.deque([root])
res = 1
while queue:
while que: depth += 1
for _ in range(len(que)): for _ in range(len(queue)):
node = que.popleft() node = queue.popleft()
# 当左右孩子都为空的时候,说明是最低点的一层了,退出
if not node.left and not node.right: if not node.left and not node.right:
return res return depth
if node.left is not None:
que.append(node.left) if node.left:
if node.right is not None: queue.append(node.left)
que.append(node.right)
res += 1 if node.right:
return res queue.append(node.right)
return depth
``` ```