【Leetcode刷题Python】111. 二叉树的最小深度
2023-09-14 09:13:02 时间
1 题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
2 解析
递归计算每个子树的最小深度
3 Python实现
class Solution:
def minDepth(self, root: Optional[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 MySQLdb模块连接操作mysql数据库实例_python
- python socket编程
- python监控linux某个端口的消息报文往来
- Python 与时间、日期相关的库 time, datetime, calendar
- Python 刷Leetcode题库,顺带学英语单词(44)
- Python爬虫开发:ip代理的使用
- Python之tkinter:动态演示调用python库的tkinter带你进入GUI世界(text.insert/link各种事件)
- Python编程语言学习:python中与数字相关的函数(取整等)、案例应用之详细攻略
- Python:Python多种集成开发环境(IDE,编译器)的简介、安装、入门、使用方法之详细攻略
- python中异常的姓名
- Python爬虫:browsercookie库获取浏览器cookie
- 【Leetcode刷题Python】206.反转链表
- 【Leetcode刷题Python】102. 二叉树的层序遍历
- 【Leetcode刷题Python】94. 二叉树的中序遍历
- 【Leetcode刷题Python】矿泉水问题
- 【Leetcode刷题Python】64. 最小路径和
- 【Leetcode刷题Python】110. 平衡二叉树
- 【Leetcode刷题Python】104. 二叉树的最大深度
- 【Leetcode刷题Python】297. 二叉树的序列化与反序列化
- 【Leetcode刷题Python】1143. 最长公共子序列
- 【Leetcode刷题Python】96. 不同的二叉搜索树
- Python: Ansible
- Python可视化数据分析01、python环境搭建