minimum depth of binary tree

这题easy,不过可以好好体会下Divide and Conquer的解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class (object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and not root.right:
return 1
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if not root.left:
return right + 1
if not root.right:
return left + 1
return min(left, right) + 1