111. 二叉树的最小深度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root==None:
return 0
left_index = self.minDepth(root.left)
right_index = self.minDepth(root.right)
if root.left==None and root.right!=None:
return right_index + 1
if root.left!=None and root.right==None:
return left_index + 1
return min(left_index,right_index) + 1