一.题目:
给一颗二叉树,求它的最小深度
二.解题思路:
给定根节点,我们只需要计算它的左子树的最小深度和右子树的最小深度的较小值+1.所以我们的递归函数就出来了,代码如下:
# 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 and root.right == None:
return 1
if root.left == None and root.right != None:
return self.minDepth( root.right ) + 1
if root.left != None and root.right == None:
return self.minDepth( root.left ) + 1
return min( self.minDepth( root.left ), self.minDepth( root.right ) ) + 1