python - 递归到迭代 - AVL 树 - isBalanced

标签 python algorithm recursion avl-tree iteration

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

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

这是递归版本的源代码(用Python编写)

def isBalanced(root):
    if root == None:
        return -1

    lh = isBalanced(root.left)
    rh = isBalanced(root.right)

    if lh == -2 or rh == -2:
        return -2

    if abs(lh - rh) > 1:
        return -2

    return max(lh, rh) + 1

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

提前致谢

最佳答案

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

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是要检查的节点堆栈,以及这些节点的结果。

关于python - 递归到迭代 - AVL 树 - isBalanced,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23037034/

相关文章:

python - Pandas:df.groupby() 对于大数据集来说太慢了。任何替代方法?

python - 无法从牧师模块中 pickle 贝叶斯对象

java - java中的阶乘递归 "visualized"

javascript - 如何通过回溯递归地修改数组元素?

python - 如何在 Python 中使用 BeautifulSoup 删除 HTML 标签之间的空格?

python - 另一个类的方法在调用时不能完全工作

algorithm - 哪个算法分配类次(离散优化问题)

c++ - 在 O(min(log(n),log(m)) 复杂度中找到两个不同大小的排序数组的中位数

javascript - jQuery - 在色轮上获取白色或深色文本

emacs - 在Elisp中的lambda递归