I have a tree of nodes like this:
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.
Since I can’t know in advance how large the model is, I’ve reached the conclusion that recursion is not an option. I would like to keep as few nodes in memory as possible. This is what my method should print:
- 0
-- 0:0
--- 0:0:0
--- 0:0:1
---- 0:0:1:0
---- 0:0:1:1
--- 0:0:2
-- 0:1
- 1
But this is what it does print:
- 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
Here’s the code I’ve written:
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))
Any help is greatly appreciated.
Since each node has a reference to its parent, I think you can traverse the whole tree keeping only one node in memory at a time. I had a bit of trouble understanding your code (in particular how each node is loaded to memory), so I’ll post my suggestion in pseudo-code:
If the node itself must be dynamically loaded (i.e.
next,prev,parentandchildrenonly contain the path to another node’s data, not a reference to aNodeobject), tell me and I’ll update the answer (just need to change a little the places for loading/unloading). Of course, if unloading is just a matter of leaving the object to the garbage collector, it’s even easier…