您的位置:首页 > 其它

【LEETCODE】111-Minimum Depth of Binary Tree

2015-10-31 19:56 471 查看
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.

# 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:                                          #root为空,返回0
return 0
elif root.left != None and root.right == None:            #只有左子树时,不用考虑右子树的深度,否则会返回1,但是无意义的
return self.minDepth(root.left)+1
elif root.left == None and root.right != None:            #同理,只有右子树时
return self.minDepth(root.right)+1
else:
return min(self.minDepth(root.left),self.minDepth(root.right))+1      #左右子树都有时,返回最小的深度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: