mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加0111.二叉树的最小深度 Python版本。
This commit is contained in:
@ -195,9 +195,51 @@ public:
|
||||
|
||||
Java:
|
||||
|
||||
|
||||
Python:
|
||||
|
||||
递归法:
|
||||
|
||||
```python
|
||||
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
|
||||
if root.left:
|
||||
min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度
|
||||
if root.right:
|
||||
min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度
|
||||
return min_depth + 1
|
||||
```
|
||||
|
||||
迭代法:
|
||||
|
||||
```python
|
||||
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()
|
||||
# 当左右孩子都为空的时候,说明是最低点的一层了,退出
|
||||
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
|
||||
```
|
||||
|
||||
|
||||
Go:
|
||||
|
||||
|
Reference in New Issue
Block a user