leetcode_111. 二叉树的最小深度 python
2020-08-25 23:00
1221 查看
目录
一、题目内容
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
二、解题思路
1.由于是最小深度,因此需要递归地比较左右子树的深度大小,取小者。
2.若没有子树则深度加0,若只有左子树或右子树或二者都有则深度加“1和子树的深度二者之和”。
三、代码
[code]# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ def iter_depth(root): if root is None: return 0 if root.left is None and root.right is not None: return 1 + iter_depth(root.right) if root.left is not None and root.right is None: return 1 + iter_depth(root.left) return 1 + min(iter_depth(root.left), iter_depth(root.right)) return iter_depth(root)悲恋花丶无心之人 CSDN认证博客专家 TensorFlow 深度学习 神经网络 计算机视觉在读研究生,熟悉Pytorch,MXNet,TensorFlow,Keras等深度学习框架,主要涉及的领域有目标检测,语义分割,超分辨率重建,行人重识别等。
相关文章推荐
- LeetCode 111. 二叉树的最小深度
- LeetCode - 111. 二叉树的最小深度
- leetcode111. 二叉树的最小深度
- 利用python 完成leetcode111 二叉树的最小深度
- Leetcode 111 python 二叉树的最小深度
- [LeetCode题解] 111. 二叉树的最小深度
- [Leetcode] 104. 二叉树的最大深度与111. 二叉树的最小深度 java
- LeetCode-111. 二叉树的最小深度(C语言)
- LeetCode 111. 二叉树的最小深度
- Leetcode 111. 二叉树的最小深度
- LeetCode刷题之路---111. 二叉树的最小深度
- LeetCode写题历程——111. 二叉树的最小深度
- 【LeetCode】111. 二叉树的最小深度
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- leetcode111_二叉树最小深度
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- [Leetcode] The minimum depth of binary tree二叉树的最小深度
- [LeetCode]111. Minimum Depth of Binary Tree--二叉树的最小深度
- leetcode 二叉树的最小深度