根据题目描述,最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
在一段没有root.left时候最小深度为root.right+1,采用递归方法解决问题,下面是代码
if not root:
return 0
if not root.left:
return 1+self.minDepth(root.right)
if not root.right:
return 1+self.minDepth(root.left)
else:
return 1+min(self.minDepth(root.right),self.minDepth(root.left))
二叉树最小深度的层次打印方法
算法遍历二叉树的每一层,发现某一层无子节点返回其深度,这个深度就是二叉树的最小深度。
if not root:
return 0
p=[root]
depth = 1
while p is not []:
t=[]
for i in p:
if not i.left and not i.right:
return depth
if i.left:
t.append(i.left)
if i.right:
t.append(i.right)
p=t
depth += 1
return depth