Merge pull request #2075 from jianghongcheng/master

跟新python代码,已经检查
This commit is contained in:
程序员Carl
2023-05-05 08:56:35 +08:00
committed by GitHub
18 changed files with 973 additions and 582 deletions

View File

@@ -305,46 +305,98 @@ 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
```
迭代法:
```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