【Leetcode】104. Maximum Depth of Binary Tree

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

1. 描述

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nYXAYdFu-1637256652842)(../../pictureSto/image-20211118101440539.png)]

2. 解决

2.1 递归(DFS——深度优先)

关于递归:想出能够表示递归函数意义的那行代码即可,别的不用多想。

递归思想:

  • 左子树深度与右子树深度中较大的一个

时间复杂度: O(n),其中 n 为二叉树节点的个数。每个节点在递归中只被遍历一次。

空间复杂度: O(h),其中 h 表示二叉树的高度。递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxDepth(self, root):  # 递归函数需要的意义:左右子树高度中较大的那个
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:  # 无根→ 0
            return 0
        else:  # 有根
            LHeigh = self.maxDepth(root.left)  ## 左子树的左子树的高度 和 左子树的右子树的高度中较大的那个
            RHeigh = self.maxDepth(root.right)  ## 右子树的左子树的高度 和 右子树的右子树的高度中较大的那个
            MaxHeigh = max(LHeigh, RHeigh)  # →递归意义的实现,左右子树高度中较大的那个
        
        return MaxHeigh + 1  # 最后,左右子树最大高度 + 根节点→ 整棵树的高度

2.2 迭代(BFS——广度优先)

迭代思想:

  • BFS 的核心数据结构是队列
  • 与每次 pop 出一个元素不同,此时应该每次 pop 出当前层的所有元素

总结来说一句话:删除当前层所有元素,加入下一层的所有元素,迭代次数即为所求。 迭代出口为“队列为空”,即已到达最下面的一层了。

时间复杂度: O(n),其中 n 为二叉树的节点个数。与方法一同样的分析,每个节点只会被访问一次。

空间复杂度: 此方法空间的消耗取决于队列存储的元素数量,其在最坏情况下会达到 O(n)。

# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:  # 无根→ 0
            return 0
        res = 0  # 初始值为 0
        queue = [root]  # 初始列表(队列)
        while queue:  # 迭代出口:队列为空
            size = len(queue)
            for i in range(size):  # 删除当前层所有元素,(即,i次pop),加入下一层的所有元素
                cur = queue.pop(0)
                # 添加下一层的元素
                if cur.left:  
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
                    
            # 每迭代 1 次,res += 1。迭代次数即为所求。
            res += 1
    
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值