如何提高在python中确定树是否为AVL树的效率?

如何提高在python中确定树是否为AVL树的效率?,python,recursion,avl-tree,Python,Recursion,Avl Tree,目前,在我下面的代码中有两个递归层。我想知道,在代码更高效的意义上,是否可以“合并”这两者 class Solution(object): def maxDepth(self, root): if root == None: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right))+1 def isBalanced(self, root

目前,在我下面的代码中有两个递归层。我想知道,在代码更高效的意义上,是否可以“合并”这两者

class Solution(object):
    def maxDepth(self, root):
        if root == None:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right))+1

    def isBalanced(self, root):

        if root == None:
            return True
        if abs(self.maxDepth(root.left) - self.maxDepth(root.right)) <= 1:
            return self.isBalanced(root.left) and self.isBalanced(root.right)
        return False
类解决方案(对象):
def maxDepth(自,根):
如果根=无:
返回0
返回最大值(self.maxDepth(root.left)、self.maxDepth(root.right))+1
def isBalanced(自平衡、根平衡):
如果根=无:
返回真值

如果abs(self.maxDepth(root.left)-self.maxDepth(root.right))要定义一个函数来检查树是否完全平衡,那么您只能使用以下伪代码中给出的算法访问一次树(我不知道足够的Python语法来编写显式代码):

基本上,如果子树是平衡的或不是平衡的,算法会递归地访问树,如果是平衡的,则会访问树的深度

命令“exit from The function”应该导致立即退出函数的所有递归调用(如果在Python中可以),否则它只是从当前调用返回指定的元组

当然,在函数的末尾,只有元组的第一个组件(关于平衡性的信息)是有用的


如果要检查一棵树是否平衡,且树叶深度的差异最大为1,则可以通过返回包含三个元素(平衡、最小深度、最大深度)的元组来扩展此解决方案,并在一般情况下检查子树的深度(最小和最大)是否一致(然后返回当前的最小值和最大值)。

以下是对以下内容的Python翻译:


合并代码并不意味着它会更有效。
isBalanced(tree):
  if tree is null 
  then return the tuple (true, 0)
  else be (bal1, lev1) the result of calling isBalanced on the left child of tree
   and be (bal2, lev2) the result of calling isBalanced on the rigth child of tree
     if (bal1 is false) or (bal2 is false)
     then exit from the function with the tuple (false, 0)
     else if lev1 = lev2
          then return the tuple (true, 1+lev1)
          else exit from the function with the tuple (false, 0)
class Tree:
    def __init__(self, left=None, right=None):
        self.left = left
        self.right = right


def isBalanced(tree):
    exitValue = None

    def isBalancedCore(tree):
        nonlocal exitValue
        if exitValue is not None:
            return exitValue

        if tree is None:
            return (True, 0)
        else:
            bal1, lev1 = isBalancedCore(tree.left)
            bal2, lev2 = isBalancedCore(tree.right)
            if not bal1 or not bal2:
                exitValue = (False, 0)
                return exitValue
            elif lev1 == lev2:
                return (True, lev1+1)
            else:
                exitValue = (False, 0)
                return exitValue

    return isBalancedCore(tree)[0]