LeetCode-Python-111. 二叉树的最小深度

本文探讨了二叉树最小深度的两种算法实现,一种是通过遍历所有路径并记录长度,另一种是采用递归方式根据子树状态计算。通过示例展示了如何找到从根节点到最近叶子节点的最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

第一种比较麻瓜的思路:

先找到所有路径,把它们的长度存到一个数组里,然后返回这个数组的最小值

第二种从讨论区学来的思路:

递归地扫每个node,根据每个node当前左右子树的状态返回相应的表达式

 

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.depth_list = list()
        self.findAllDepth(root, 0)
        print self.depth_list
        return min(self.depth_list)
    
    def findAllDepth(self, node, depth):
        if not node.left and not node.right:
            depth += 1
            self.depth_list.append(depth)
            return
        if node.left:
            self.findAllDepth(node.left, depth + 1)
        if node.right:
            self.findAllDepth(node.right, depth + 1)
        return
=========================================================
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root:
            if root.left and root.right:
                return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
            if root.left:
                return 1 + self.minDepth(root.left)
            if root.right:
                return 1 + self.minDepth(root.right)
            else:
                return 1
        else:
            return 0
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值