Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无递归打印树_Python_Recursion - Fatal编程技术网

Python 无递归打印树

Python 无递归打印树,python,recursion,Python,Recursion,我有以下代码,用于打印树中每个节点的数据: class Node: def __init__(self,data, children=[]): self.data = data self.children = children def __repr__(self): return str(self.data) n1 = Node(1) n2 = Node(2) n3 = Node(3) n4 = Node(4) n5 = Node

我有以下代码,用于打印树中每个节点的数据:

class Node:
    def __init__(self,data, children=[]):
        self.data = data
        self.children = children
    def __repr__(self):
        return str(self.data)

n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
n6 = Node(6)
n7 = Node(7)


n1.children=[n2,n3,n4]
n3.children = [n5,n6]
n6.children=[n7]

def print_rec(node):
    print node
    if not node.children: return
    for c in node.children:
        printer(c)

如何在不使用递归的情况下编写print_rec方法?

您可以使用队列跟踪仍要处理的节点,并在处理节点时添加到队列中:

def print_nonrec_breathfirst(node):
    queue = [node]
    while queue:
        node, queue = queue[0], queue[1:]
        print node
        for c in node.children:
            queue.append(c)
或者可以使用堆栈,首先处理子对象:

def print_nonrec_depthfirst(node):
    stack = [node]
    while stack:
        node = stack.pop()
        print node
        for c in node.children:
            stack.append(c)
无论哪种方式,您都可以跟踪哪些节点尚未打印,并且在处理节点时,您还可以确定哪些子节点仍然需要处理

演示:


这真是太棒了。但是有没有更“简单”(易于掌握)的方法呢?@Kipi-Well。。。递归;-)
if not node.children:continue
是没有意义的-当
node.children
是空列表/元组时,for的主体在它之后根本不会被执行。我正在理解解决方案代码。但这不是思考此类问题的方法。@Kipi,除非您将其重命名为
queue
。您还可以使用
collections.deque
。我觉得使用切片很好地说明了所发生的事情。
>>> print_nonrec_breathfirst(n1)
1
2
3
4
5
6
7
>>> print_nonrec_depthfirst(n1)
1
4
3
6
7
5
2