Python 递归到迭代-AVL树-isBalanced

Python 递归到迭代-AVL树-isBalanced,python,algorithm,recursion,avl-tree,iteration,Python,Algorithm,Recursion,Avl Tree,Iteration,我必须编写一个迭代算法来确定AVL树是否平衡 我的第一个方法是找到一种直接的方法,但几个小时后我放弃了,所以我编写了递归算法并尝试将其转换 下面是递归版本(用python编写)的源代码 我现在的问题是,我无法转换它,也许你们中的一个可以给我一个提示或解决我的问题 提前感谢记住递归程序使用调用堆栈。您可以使用堆栈将任何递归程序转换为迭代程序。在下面的代码中,我使用了两个 def isBalanced(root): nodes = [root] results = [] wh

我必须编写一个迭代算法来确定AVL树是否平衡

我的第一个方法是找到一种直接的方法,但几个小时后我放弃了,所以我编写了递归算法并尝试将其转换

下面是递归版本(用python编写)的源代码

我现在的问题是,我无法转换它,也许你们中的一个可以给我一个提示或解决我的问题


提前感谢

记住递归程序使用调用堆栈。您可以使用堆栈将任何递归程序转换为迭代程序。在下面的代码中,我使用了两个

def isBalanced(root):
    nodes = [root]
    results = []
    while nodes:
        node = nodes.pop()
        if node is None:
            results.append(-1)
        else if node == 0: # 0 is a flag we use for when we are ready to combine results
            lh = results.pop()
            rh = results.pop()
            if abs(lh - rh) > 1:
                return -2  # we could have continued with the stack; this is just a shortcut
            else:
                results.append(max(lh, rh) + 1)
        else:
            nodes.push(0)
            nodes.push(node.left)
            nodes.push(node.right)
    return results, # results will have only one value

这里,
stack
是要检查的节点堆栈,以及这些节点的结果。

记住递归程序使用调用堆栈。您可以使用堆栈将任何递归程序转换为迭代程序。在下面的代码中,我使用了两个

def isBalanced(root):
    nodes = [root]
    results = []
    while nodes:
        node = nodes.pop()
        if node is None:
            results.append(-1)
        else if node == 0: # 0 is a flag we use for when we are ready to combine results
            lh = results.pop()
            rh = results.pop()
            if abs(lh - rh) > 1:
                return -2  # we could have continued with the stack; this is just a shortcut
            else:
                results.append(max(lh, rh) + 1)
        else:
            nodes.push(0)
            nodes.push(node.left)
            nodes.push(node.right)
    return results, # results will have only one value

这里,
stack
是一个要检查的节点堆栈,以及这些节点的结果。

您需要从叶子开始,因为递归所做的是向下到叶子,并将子树的高度传播到根。您需要从叶子开始,因为递归所做的是向下到叶子,并将子树的高度传播到根。