我有節點的樹是這樣的:樹模型的迭代印刷
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