问题描述
https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
解题思路
这个题目不难,但对退出条件要求高。
经过对题意的分析,我们对于root为None的情况,以及root为叶子结点的情况,以及root只有左子树、右子树的情况,以及root有左子树和右子树的情况都进行处理才行。
代码
# 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 is None: return 0 if root.left is None and root.right is None: return 1 if root.left is None: return self.minDepth(root.right)+1 if root.right is None: return self.minDepth(root.left)+1 return min(self.minDepth(root.left), self.minDepth(root.right))+1
标签:None,right,return,self,最小,111,二叉树,root,left From: https://www.cnblogs.com/bjfu-vth/p/17070561.html