返回

揭秘二叉树的最大深度:通俗易懂的算法详解,扫清你的疑惑!

前端

二叉树的最大深度:通俗易懂的算法详解

二叉树是一种非线性数据结构,由节点和边组成。每个节点可以包含数据,也可以是空节点。二叉树的最大深度是指从根节点到最深的叶节点的路径上的节点数。

求解二叉树的最大深度有很多种方法,其中最常见的方法是递归和深度优先搜索。

递归法

递归法是一种很自然的方法,它通过递归的方式来计算二叉树的最大深度。

def max_depth(root):
    if root is None:
        return 0
    left_depth = max_depth(root.left)
    right_depth = max_depth(root.right)
    return max(left_depth, right_depth) + 1

深度优先搜索

深度优先搜索也是一种常用的方法,它通过深度优先的方式来计算二叉树的最大深度。

def max_depth(root):
    if root is None:
        return 0
    stack = [(root, 1)]
    max_depth = 0
    while stack:
        node, depth = stack.pop()
        max_depth = max(max_depth, depth)
        if node.left is not None:
            stack.append((node.left, depth + 1))
        if node.right is not None:
            stack.append((node.right, depth + 1))
    return max_depth

LeetCode题目解析

LeetCode题目的给定函数原型为:

def maxDepth(self, root: Optional[TreeNode]) -> int:

给定二叉树的根节点root,返回它的最大深度。

我们可以使用递归或深度优先搜索方法来解决这个问题。

def maxDepth(self, root: Optional[TreeNode]) -> int:
    if root is None:
        return 0
    left_depth = self.maxDepth(root.left)
    right_depth = self.maxDepth(root.right)
    return max(left_depth, right_depth) + 1

总结

二叉树的最大深度是一个经典的算法题,它有多种解法。在本文中,我们介绍了递归法和深度优先搜索两种解法。此外,我们还给出了LeetCode题目的解析。希望本文对大家学习二叉树的最大深度算法有所帮助。

扩展阅读