二叉树的最大深度(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
相关推荐
SNWCC16 小时前
autodl_M000_pytorch
人工智能·pytorch·python
biubiuibiu16 小时前
选择适合的硬盘:固态与机械硬盘的对比与推荐
c++·算法
big_rabbit050216 小时前
[算法][力扣226]翻转一颗二叉树
数据结构·算法·leetcode
TracyCoder12316 小时前
LeetCode Hot100(65/100)——64. 最小路径和
算法·leetcode·职场和发展
z2014z16 小时前
Deflate 算法详解
网络·算法
条tiao条16 小时前
从 “Top-K 问题” 入门二叉堆:C 语言从零实现与经典应用
c语言·算法·深度优先
uesowys16 小时前
华为OD算法开发指导-数据结构-图
数据结构·算法·华为od
实心儿儿16 小时前
算法3:链表分割
数据结构·算法·链表
deephub16 小时前
多智能体系统的三种编排模式:Supervisor、Pipeline 与 Swarm
人工智能·python·大语言模型·agent
m0_7381207217 小时前
渗透测试——pyexpvm靶机详细提权过程(MSF框架,Hydra数据库爆破,SUDO提权)
服务器·网络·数据库·python·sql·web安全