如何在python中迭代二叉搜索树(无递归)

时间:2014-03-31 01:55:19

标签: python loops binary-search-tree

到目前为止我已经

def tree_iterate():
parent, current = None, self.root
lst = []
while current is not None: 
 if current.left not None:
  lst.append(current.item) 
  parent, current = current, current.left
 if current.right not None:
  lst.append(current.item)
  parent, current = current, current.right

(对不起我的间距我很陌生)

我不太确定如何在当前左右移动时在树的两侧进行迭代,而不使用递归。我的主要目标是拥有此BST enter code here

中所有节点的列表

1 个答案:

答案 0 :(得分:3)

要迭代地获取BST中所有节点的列表,请使用广度优先搜索(BFS)。请注意,这不会按排序顺序为您提供节点:

level = [root]
nextLevel = []
queue = []
while not level:
    queue.extend(level)
    for l in level:
        nextLevel.append(l.left if l.left != None)
        nextLevel.append(l.right if l.right != None)
    level = nextLevel
    nextLevel = []

如果您希望节点按排序顺序排列,则需要使用堆栈模拟inorder遍历:

result = []
stack = [root]
while stack:
    stack[-1].visited = True
    if stack[-1].left != None and not stack[-1].left.visited:
        stack.append(stack[-1].left)
    else:
        node = stack.pop()
        result.append(node)
        if stack[-1].right != None:
            stack.append(stack[-1].right)