二叉树的最大深度(LeetCode)

题目

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

解题

python 复制代码
# 定义二叉树节点的类
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# 计算二叉树最大深度的函数
def maxDepth(root: TreeNode) -> int:
    # 如果当前节点为空,则深度为0
    if not root:
        return 0

    # 递归计算左子树和右子树的深度
    left_depth = maxDepth(root.left)
    right_depth = maxDepth(root.right)

    # 返回左子树和右子树深度的较大者 + 1
    return max(left_depth, right_depth) + 1


# 创建二叉树
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20, TreeNode(15), TreeNode(7))

# 计算最大深度
depth = maxDepth(root)
print(depth)  # 输出 3
相关推荐
JieE2128 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵13 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1118 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0020 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent