# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution(object):defminDepth(self,root):""" :type root: TreeNode :rtype: int """returnself.depth(root,layer=0)defdepth(self,root,layer):ifroot==None:returnlayerlayer+=1ifnotroot.leftandnotroot.right:# it's a leaf, return layer directlyreturnlayerifroot.leftandroot.right:# has left and right, find minreturnmin(self.depth(root.left,layer),self.depth(root.right,layer))ifroot.left:# if left or right, it is not a leafreturnself.depth(root.left,layer)ifroot.right:# if left or right, it is not a leafreturnself.depth(root.right,layer)
近期评论