求给定二叉树的最大深度

求给定二叉树的最大深度,
深度是指树的根节点到任一叶子节点路径上节点的数量。
最大深度是所有叶子节点的深度的最大值。

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:
    if not root:
        return 0
    left_depth = maxDepth(root.left)
    right_depth = maxDepth(root.right)
    return max(left_depth, right_depth) + 1

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

# 计算最大深度
print(maxDepth(root))

以下是一个求二叉树最大深度的 Python 代码,使用了递归方法:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def max_depth(root: TreeNode) -> int:
    """
    返回二叉树的最大深度
    """
    if not root:
        return 0
    left_depth = max_depth(root.left)
    right_depth = max_depth(root.right)
    return max(left_depth, right_depth) + 1

在这个函数中,我们首先判断给定的二叉树是否为空,如果为空则返回深度为 0。否则,我们分别递归求出左子树和右子树的深度,然后取两者的较大值再加1,即为整棵树的深度,最终返回深度值。

该算法的时间复杂度为 O(n),其中 n 是二叉树节点的数量。因为需要遍历整棵树一次,访问每个节点恰好一次,所以时间复杂度为 O(n)。空间复杂度为 O(h),其中 h 是二叉树的高度,即递归栈的最大深度,最坏情况下为 O(n)(完全不平衡二叉树)。