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.
判断树的最小深度~树的最小深度指的是从根节点到最近的叶节点的距离,所以如果某一个节点只有左子树或右子树,我们不能取它左右子树中小的作为深度,因为其并非叶节点,要注意处理这种情况~下面代码是递归的解法~
class Solution:
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root is None: return 0
if root.left is None: return self.minDepth(root.right) + 1
if root.right is None: return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
知道递归解法还不够,最好也能写出非递归解法~代码如下~(注意:python中list.pop(0)时间复杂度为O(n),所以下面curr = queue.pop(0)这句不是很高效)
class Solution:
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root is None: return 0
queue = [root, None]; depth = 1
while queue:
curr = queue.pop(0)
if curr == None:
# note: do not increase depth if queue
# is empty;
if queue:
queue.append(None)
depth += 1
else:
if curr.left is None and curr.right is None:
return depth
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)