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