打印树没有递归

时间:2014-11-02 13:50:22

标签: 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(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方法?

1 个答案:

答案 0 :(得分:2)

您使用队列来跟踪仍要处理的节点,并在处理它们时添加它:

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)

无论哪种方式,您都会跟踪尚未打印的节点,并且在处理节点 还要找出您仍需要处理的子节点

演示:

>>> print_nonrec_breathfirst(n1)
1
2
3
4
5
6
7
>>> print_nonrec_depthfirst(n1)
1
4
3
6
7
5
2