两种解法:
(1)深度优先遍历,与maximum depth of binary tree类似,时间复杂度,递归函数栈结构空间复杂度,但需要考虑两种情况:
i. 节点返回时必须为叶子节点,返回深度应该为1。
ii. 为了满足i.实现时要返回非空子树的最小深度。
(2)广度优先遍历,优势在于,深度优先遍历会遍历全部子树,这在树非常不平衡时效率比较低。可以采用广度优先遍历来克服这一问题。时间复杂度,最差情况的空间复杂度
Python源码:
Runtime: 28 ms, faster than 90.02% of Python online submissions for Minimum Depth of Binary Tree.
Memory Usage: 14.5 MB, less than 94.87% of Python online submissions for Minimum Depth of Binary Tree.
# 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
"""
if root == None:
return 0
depth = 0
found_leaf = False
cur_nodes = [root]
while not found_leaf:
next_nodes = []
while cur_nodes:
if cur_nodes[-1].left != None:
next_nodes.append(cur_nodes[-1].left)
if cur_nodes[-1].right != None:
next_nodes.append(cur_nodes[-1].right)
if cur_nodes[-1].left == None and cur_nodes[-1].right == None:
found_leaf = True
break
cur_nodes.pop()
depth += 1
cur_nodes = next_nodes
return depth
我的心路:
类似maximum depth of binary tree,依然采用递归法,把max函数改为min函数,但minimum depth需要多考虑的一个问题是,只有叶子节点可以返回深度,而maximum是无需考虑这一点的。所以要事先排除非叶子节点的返回。时间复杂度,递归函数栈结构空间复杂度。
Runtime: 40 ms, faster than 21.58% of Python online submissions for Minimum Depth of Binary Tree.
Memory Usage: 14.9 MB, less than 20.51% of Python online submissions for Minimum Depth of Binary Tree.
# 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
"""
if root == None:
return 0
if root.left == None:
return self.minDepth(root.right) + 1
elif root.right == None:
return self.minDepth(root.left) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right))+1