leetcode111. 二叉树的最小深度python

题目描述:

 题解:

采用DFS方法:

DFS对二叉树从根节点开始搜索,根结点位置depth为1

列表depthlist保存叶子结点对应的depth

然后depth+1在root的左右子节点分别调用DFS函数

class Solution(object):
    def minDepth(self, root):
        if root is None:
            return 0
        depth = 1
        depthlist = []
        depthlist = self.DFS(root,depth,depthlist)
        mindepth = min(depthlist)
        return mindepth

    def DFS(self,root,depth,depthlist):
        if root==None:
            return 0
        if root.left==None and root.right==None:
            depthlist.append(depth)
        self.DFS(root.left,depth+1,depthlist)
        self.DFS(root.right,depth+1,depthlist)
        return depthlist

LeetCode-111- 二叉树的最小深度(python) - 简书提供了一种更简单的解法。

class Solution(object):
    def minDepth(self,root):
        if root==None:
            return 0
        if root.left==None and root.right==None:
            return 1
        if root.left==None:
            return self.minDepth(root.right)+1
        if root.right==None:
            return self.minDepth(root.left)+1
        return min(self.minDepth(root.left),self.minDepth(root.right))+1

二叉树的最小深度有以下几种情况:

1.root为空,最小深度为0

2.root不为空,但root左右子树为空,最小深度为1

3.root左子树为空,最小深度为右子树最小深度+1

4.root右子树为空,最小深度为左子树最小深度+1

5.左右子树都存在,最小深度=min(左子树最小深度,右子树最小深度)+1

注意:对左右子树是否为空的判断不能缺少,比如题目中示例2的情况,二叉树为:

 此时左子树为空,会返回0的最小深度,如果直接使用min(self.minDepth(root.left),self.minDepth(root.right))+1求解,会得到最小深度为1的错误答案。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值