给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
第一种比较麻瓜的思路:
先找到所有路径,把它们的长度存到一个数组里,然后返回这个数组的最小值
第二种从讨论区学来的思路:
递归地扫每个node,根据每个node当前左右子树的状态返回相应的表达式
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.depth_list = list()
self.findAllDepth(root, 0)
print self.depth_list
return min(self.depth_list)
def findAllDepth(self, node, depth):
if not node.left and not node.right:
depth += 1
self.depth_list.append(depth)
return
if node.left:
self.findAllDepth(node.left, depth + 1)
if node.right:
self.findAllDepth(node.right, depth + 1)
return
=========================================================
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root:
if root.left and root.right:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
if root.left:
return 1 + self.minDepth(root.left)
if root.right:
return 1 + self.minDepth(root.right)
else:
return 1
else:
return 0