Python 如何将查找二叉树中两个级别之间节点的递归实现转换为迭代版本?

Python 如何将查找二叉树中两个级别之间节点的递归实现转换为迭代版本?,python,recursion,tree,binary-tree,Python,Recursion,Tree,Binary Tree,这就是我构建二叉树的方式: class BinaryTree(): def __init__(self, value): self.key = value self.left = None self.right = None t2 = BinaryTree(20) t2.left = BinaryTree(8) t2.left.left = BinaryTree(4) t2.left.right = BinaryTree(12) t2.l

这就是我构建二叉树的方式:

class BinaryTree():
    def __init__(self, value):
        self.key = value
        self.left = None
        self.right = None

t2 = BinaryTree(20)
t2.left = BinaryTree(8)
t2.left.left = BinaryTree(4)
t2.left.right = BinaryTree(12)
t2.left.right.left = BinaryTree(10)
t2.left.right.right = BinaryTree(14)
t2.right = BinaryTree(22)
这是我的递归函数,它返回两个级别之间的节点:

def find_nodes_between_two_levels(tree, high, low, currentLevel=1, output=None):
    if output is None:
        output = {}

    if tree is None or currentLevel > low:
        return

    if currentLevel >=high and currentLevel<=low:
        if currentLevel not in output:
            output[currentLevel] = [tree.key]
        else:
            output[currentLevel].append(tree.key)
    nextLevel = currentLevel + 1
    find_nodes_between_two_levels(tree.left, high, low, nextLevel, output)
    find_nodes_between_two_levels(tree.right, high, low, nextLevel, output)

    return output

这个问题的迭代解决方案是什么?

因为这个函数不是尾部递归的,所以迭代解决方案需要通过堆栈或队列来维护您自己的状态。就我个人而言,对于这类问题,我可能会使用队列方法并进行树的广度优先遍历

def find_nodes_between_two_levels(root, high, low):
    from collections import defaultdict
    output = defaultdict(list)
    queue = [(root, 1)]
    while queue:
        tree, level = queue.pop()
        if not tree or level > low:
            continue
        if high <= level <= low:
            output[level].append(tree.key)
        level += 1
        queue.append((tree.left, level))
        queue.append((tree.right, level))
    return output
def find_nodes_位于两个_级别(根、高、低)之间:
从集合导入defaultdict
输出=默认DICT(列表)
队列=[(根,1)]
排队时:
树,级别=queue.pop()
如果不是树或级别>低:
持续

如果很高,非常感谢!特别是解释如何用显式队列替换隐式堆栈可以将其转化为迭代解决方案。@user3390764如果有某种方法可以避免堆栈溢出的话。
def find_nodes_between_two_levels(root, high, low):
    from collections import defaultdict
    output = defaultdict(list)
    queue = [(root, 1)]
    while queue:
        tree, level = queue.pop()
        if not tree or level > low:
            continue
        if high <= level <= low:
            output[level].append(tree.key)
        level += 1
        queue.append((tree.left, level))
        queue.append((tree.right, level))
    return output