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:
|
Java:
|
||||||
|
|
||||||
|
|
||||||
Python:
|
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:
|
Go:
|
||||||
|
|
||||||
@ -208,4 +250,4 @@ Go:
|
|||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
Reference in New Issue
Block a user