LintCode Q115 Minimum Depth of Binary Tree in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年12月10日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def minDepth(self, root):
# write your code here
# time complexity O(n), n number of nodes
if root is None:
return 0
if root.left is None and root.right is None:
return 1
else:
if root.left is None:
return 1 + self.minDepth(root.right)
elif root.right is None:
return 1 + self.minDepth(root.left)
else: # left and right
return 1 + min(self.minDepth(root.right), self.minDepth(root.left))
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。