leetcode:Minimum Depth of Binary Tree【Python版】

时间:2021-09-13 03:20:19

1、类中递归调用添加self;

2、root为None,返回0

3、root不为None,root左右孩子为None,返回1

4、返回l和r最小深度,l和r初始为极大值;

 # Definition for a  binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root == None:
return 0
if root.left==None and root.right==None:
return 1
l,r = 9999,9999
if root.left!=None:
l = self.minDepth(root.left)
if root.right!=None:
r = self.minDepth(root.right)
if l<r:
return 1+l
return 1+r