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

时间:2014-07-22 02:17:58

标签: python recursion

与非嵌套版本相比,嵌套函数是否需要在堆栈中存储更多状态?如果是这样,那么额外存储的状态是什么?

代码用于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)  

当recuisive的深度很大时,递归嵌套函数会导致stackoverflow错误。

虽然以下功能可以。

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)

0 个答案:

没有答案