0
点赞
收藏
分享

微信扫一扫

Golang 字面量的表示

东林梁 2024-09-03 阅读 23

题目

解题

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

def maxDepth(root):
    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(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)

# 调用函数,输出结果
print(maxDepth(root))  # 输出3

 

举报

相关推荐

0 条评论