简体   繁体   English

如何遍历python中的二叉搜索树(无递归)

[英]how to iterate through a binary search tree in python(no recursion)

So far I have到目前为止我有

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

(sorry about spacing I'm quite new at this) (抱歉我对间距很陌生)

I'm not quite sure how to iterate on both sides of the tree when current has left and right, without using recursion.我不太确定如何在不使用递归的情况下在 current 左右时在树的两侧进行迭代。 My main goal is to have a list of all the nodes in this BST enter code here我的主要目标是列出此 BST 中所有节点的列表,在enter code here

To get a list of all nodes in the BST iteratively, use Breadth-First Search (BFS).要迭代地获取 BST 中所有节点的列表,请使用广度优先搜索 (BFS)。 Note that this won't give you the nodes in sorted order:请注意,这不会按排序顺序为您提供节点:

queue = [root]
result = []
while queue:
    l = queue.pop(0)
    result.append(l)

    if l.left != None:
        queue.append(l.left)
    if l.right!= None:
        queue.append(l.right)

If you want the nodes in sorted order, you will need to simulate inorder traversal using a stack:如果您希望节点按顺序排列,则需要使用堆栈模拟中序遍历:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM