【LeetCode】104. Maximum Depth of Binary Tree

本文介绍了如何解决LeetCode中的104题——求解二叉树的最大深度。分别讲解了使用递归和迭代两种方法的解题思路,并提供了代码实现。同时,分析了两种方法的时间和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的个人微信公众号:Microstrong

微信公众号ID:MicrostrongAI

微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!

知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

个人博客:https://blog.youkuaiyun.com/program_developer

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

解题思路:

(1)递归解法

直观的方法是通过递归来解决问题。在这里,我们演示了 DFS(深度优先搜索)策略的示例。

已经AC的代码:

from typing import List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0

        def getDepth(root):

            if root is None:
                return 0

            left_high = getDepth(root.left)

            right_high = getDepth(root.right)

            return max(left_high, right_high) + 1

        return getDepth(root)


if __name__ == "__main__":
    root = TreeNode(3)

    L1 = TreeNode(9)
    R1 = TreeNode(20)

    L2 = TreeNode(20)
    R2 = TreeNode(7)

    root.left = L1
    root.right = R1

    R1.left = L2
    R1.right = R2

    sol = Solution()
    print(sol.maxDepth(root))

复杂度分析:

  • 时间复杂度:我们每个结点只访问一次,因此时间复杂度为O(N),其中N是结点的数量。
  • 空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用N次(树的高度),因此保持调用栈的存储将是O(N)。但在最好的情况下(树是完全平衡的),树的高度将是log(N)。因此,在这种情况下的空间复杂度将是O(log(N))

(2)迭代解法

我们还可以在栈的帮助下将上面的递归转换为迭代。

我们的想法是使用 DFS 策略访问每个结点,同时在每次访问时更新最大深度。

所以我们从包含根结点且相应深度为 1 的栈开始。然后我们继续迭代:将当前结点弹出栈并推入子结点。每一步都会更新深度。

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0

        stack = [(1, root)]

        depth = 0

        while stack:
            current_depth, root = stack.pop()
            if root:
                depth = max(depth, current_depth)
                stack.append((current_depth + 1, root.left))
                stack.append((current_depth + 1, root.right))

        return depth

Reference

【1】LeetCode 题解 | 104. 二叉树的最大深度,地址:https://zhuanlan.zhihu.com/p/49972754   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值