首页 > 解决方案 > 二叉树解的最大深度的内存使用

问题描述

为什么这两种解决方案(在 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)

标签: pythonbinary-tree

解决方案


推荐阅读