为什么递归嵌套函数使用更多的堆栈sp

2024-07-04 08:15:58 发布

您现在位置:Python中文网/ 问答频道 /正文

是不是因为嵌套函数需要在堆栈中存储比非嵌套版本更多的状态?如果是这样,那么额外的存储状态是什么?你知道吗

该代码用于Leetcode Balaned Binary Tree,它使用两个递归函数。你知道吗

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

class Solution:
    # @param root, a tree node
    # @return a boolean
    def isBalanced(self, root):
        if root is None:
            return True

        def getHeight(root):
            if root is None:
                return 0
            return max(getHeight(root.left), getHeight(root.right)) + 1
        if abs(getHeight(root.left)-getHeight(root.right)) > 1:
            return False
        return self.isBalanced(root.left) and self.isBalanced(root.right)  

递归嵌套函数在递归深度较大时会产生堆栈溢出错误。你知道吗

以下功能正常。你知道吗

class Solution:
    # @param root, a tree node
    # @return a boolean
    def getHeight(self, root):
        if root is None:
            return 0
        return max(self.getHeight(root.left), self.getHeight(root.right)) + 1

    def isBalanced(self, root):
        if root is None:
            return True

        if abs(self.getHeight(root.left) - self.getHeight(root.right)) > 1:
            return False
        return self.isBalanced(root.left) and self.isBalanced(root.right)

Tags: 函数selfrightnonenodetreereturnif

热门问题