python - 二叉树解的最大深度的内存使用
问题描述
为什么这两种解决方案(在 Python 中)在查找二叉树的最大深度时内存使用量存在如此大的差异?看起来第一个解决方案使用辅助函数进行递归调用,但它与第二个解决方案做同样的事情。很难理解这一点。
~5KB 已使用
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.maxDepthH(root)
def maxDepthH(self, root):
if root == None:
return 0
else:
templ = 1 + self.maxDepthH(root.left)
tempr = 1 + self.maxDepthH(root.right)
return max(templ, tempr)
~28KB 已使用
class Solution(object):
# depth = 0
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
left = 1 + self.maxDepth(root.left)
right = 1 + self.maxDepth(root.right)
# depth = max(left, right)
return max(left, right)
解决方案
推荐阅读
- python - 计算循环中处理的元素数量的Pythonic方法
- android - 使用 Flutter 的蓝牙 SPP 服务器
- azure - Azure 函数部署在 Visual Code 中失败并出现 ETIMEDOUT 错误
- terraform - Terraform 将 VPC ID 动态添加到 Route53 区域
- python - y 包含以前看不见的标签:标签编码器中的“男性”
- azure - ASP.NET Core 3.1 无法在 Azure 服务日志流上查看我的日志
- python - 如何打印出哪个工作人员在 ray 中执行了哪些功能,而不是在仪表板上查找?
- c# - 有没有办法从 azure blob 的容器文件夹中获取所有子文件夹名称?
- geopandas - to_crs("epsg:4326") 返回不同的坐标
- amazon-web-services - AWS IAM 策略,用户应该只看到 s3 公共存储桶