Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Subscribe to see which companies asked this question
有一个点就是,如果它不是叶子节点,不能算。这个地方容易犯错。
class Solution(object):
def __init__(self):
self.minn = 99999
def dfs(self,root,lenn):
if root.left == None and root.right == None:
self.minn = min(lenn,self.minn)
return
if root.left:
self.dfs(root.left,lenn+1)
if root.right:
self.dfs(root.right,lenn+1)
def minDepth(self, root):
if not root:
return 0
self.dfs(root,1)
#print self.minn
return self.minn

本文介绍了一种求解二叉树最小深度的算法实现,通过深度优先搜索(DFS)遍历二叉树来找到从根节点到最近叶子节点的最短路径。文章提供了具体的Python代码实现,并解释了关键步骤。
4852

被折叠的 条评论
为什么被折叠?



