如何在python中迭代二进制搜索树(无递归)
到目前为止我有如何在python中迭代二进制搜索树(无递归),python,loops,binary-search-tree,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)
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
(很抱歉,我对这个很陌生)
我不太清楚,当current具有left和right时,如何在树的两侧迭代,而不使用递归。我的主要目标是获得此BST中所有节点的列表
在此处输入code
要以迭代方式获得BST中所有节点的列表,请使用广度优先搜索(BFS)。请注意,这不会按排序顺序显示节点:
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)
如果希望节点按排序顺序排列,则需要使用堆栈模拟按顺序遍历:
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)
要以迭代方式获取BST中所有节点的列表,请使用广度优先搜索(BFS)。请注意,这不会按排序顺序显示节点:
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)
如果希望节点按排序顺序排列,则需要使用堆栈模拟按顺序遍历:
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)
为什么要避免递归?这是进行树遍历的最简洁明了的方法。获取树中所有节点的一种简单迭代方法是使用广度优先搜索(BFS)。您可以使用队列(一个简单的python列表)来实现这一点。为什么要避免递归?这是进行树遍历的最简洁明了的方法。获取树中所有节点的一种简单迭代方法是使用广度优先搜索(BFS)。您可以为此使用队列(一个简单的python列表)。