我有节点的树是这样的:树模型的迭代印刷
class Node:
next # the next node or None
prev # the previous node or None
parent # the parent or None
children[] # ordered list of child nodes
columns[] # a list of data. Currently only holdt the
# string representation of the node in the model.
既然不能预先知道模型有多大,我得出一个结论,递归是不是选项。我想在内存中保留尽可能少的节点。这是我的方法应该打印的内容:
- 0
-- 0:0
--- 0:0:0
--- 0:0:1
---- 0:0:1:0
---- 0:0:1:1
--- 0:0:2
-- 0:1
- 1
但是这是它确实打印:
- 0
-- 0:0
-- 0:1
-- 0
- 1
--- 0:0:0
--- 0:0:1
--- 0:0:2
-- 0:1
-- 0
- 1
--- 0:0:1
---- 0:0:1:0
---- 0:0:1:1
--- 0:0:2
-- 0
---- 0:0:1:0
---- 0:0:1:1
--- 0:0:2
---- 0:0:1:1
---- 0:0:1:1
下面是我写的代码:
def print_tree(from_path):
nodelist = []
root_node = model.get_iter(from_path)
nodelist.append((root_node, 0)) # the second item in the tuple is the indentation
while nodelist:
node = nodelist[0][0]
indent = nodelist[0][1]
del(nodelist[0])
print("{0} {1}".format("-" * indent, node.columns[0]))
if node.children:
child = node.children[0]
nodelist.append((child, indent +1))
while child.next:
nodelist.append((child.next, indent +1))
child = child.next
if node.next:
next = node.next
nodelist.append((next, indent))
任何帮助不胜感激。
什么是'next'和'prev'?兄弟姐妹? – mgibsonbr
你能给我们一些样品数据吗? – kindall