【LEETCODE】111-Minimum Depth of Binary Tree

来源:互联网 发布:淘宝网天猫旗舰店 编辑:程序博客网 时间:2024/05/13 23:47

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 = Noneclass 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      #左右子树都有时,返回最小的深度            


0 0
原创粉丝点击