leedcode 二叉树的最小深度

自己写的:

复制代码
# 二叉树节点的定义
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:
        # 如果根节点为空,深度为0
        if not root:
            return 0

        # 如果根节点没有左子树和右子树,深度为1
        if not root.left and not root.right:
            return 1

        # 如果只有右子树,返回右子树的深度加上当前层
        if not root.left and root.right:
            right_depth = self.cal_depth(root.right)
            return right_depth + 1

        # 如果只有左子树,返回左子树的深度加上当前层
        if root.left and not root.right:
            left_depth = self.cal_depth(root.left)
            return left_depth + 1

        # 如果同时有左子树和右子树,返回左右子树深度的较小值加上当前层
        if root.left and root.right:
            return min(self.cal_depth(root.left), self.cal_depth(root.right)) + 1

    # 计算树的深度
    def cal_depth(self, root):
        # 如果根节点为空,深度为0
        if not root:
            return 0

        queue = [root]
        depth = 0

        while queue:
            level_len = len(queue)

            for i in range(level_len):
                cur_node = queue.pop(0)

                # 如果当前节点是叶子节点,返回深度(当前层)
                if not cur_node.left and not cur_node.right:
                    return depth + 1

                # 将左子节点加入队列(如果存在)
                if cur_node.left:
                    queue.append(cur_node.left)
                # 将右子节点加入队列(如果存在)
                if cur_node.right:
                    queue.append(cur_node.right)

            # 完成一层遍历,深度加1
            depth += 1

        # 遍历完整个树后,返回深度
        return depth
复制代码

gpt改进后:

复制代码
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        queue = [root]
        depth = 0

        while queue:
            # 记录当前层的节点数
            level_len = len(queue)
            depth += 1

            for i in range(level_len):
                # 弹出队列中的节点
                cur_node = queue.pop(0)

                # 如果当前节点是叶子节点,返回当前深度
                if not cur_node.left and not cur_node.right:
                    return depth

                # 将左子节点加入队列(如果存在)
                if cur_node.left:
                    queue.append(cur_node.left)
                # 将右子节点加入队列(如果存在)
                if cur_node.right:
                    queue.append(cur_node.right)
复制代码

 

posted @   Junior_bond  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示