I'm struggling with printing data from a Mtree in a visual way, more specifically this mtree https://github.com/tburette/mtree
I have a distance function here:
def d_int(x, y):
return abs(x - y)
I create and populate the MTree here
p_tree = mtree.MTree(d_int, max_node_size=2)
p_tree.add_all([1,2,6,5,0,24,19,11,80,31,32,3,4,16,71,89,9,10])
The p_tree.__dict__
looks like this:
a root with two entries (stored in a set), but with no first node. Each of the two entries then contain subtrees and so on
{'d': <function _main_.d_int(x, y)>,
(... left out data ...)
'size': 18,
'root': InternalNode(parent_node: None, parent_entry: None,
entries:[
Entry(obj: 24, dist: None, radius: 65, subtree: 'InternalNode()'),
Entry(obj: 1, dist: None, radius: 10, subtree: 'InternalNode()')
])}
I've been trying to print the tree by recursivly looping subtrees like this, but i end up with a print that does not make sence to me.
def printTree(root, level=0):
print(" " * level, root.obj)
if(root.subtree == None): return root.obj
for child in root.subtree.entries:
printTree(child, level 1)
printTree(p_tree.root.entries.pop()) //pop() because entries is a set
returns
0
11
11
11
11
11
11
10
10
0
3
3
3
4
4
3
3
6
6
6
6
5
5
9
9
9
0
0
1
1
1
2
2
0
0
0
I would also like not to have to destroy my tree (pop()) in order to print it, but I see no other way, when the root-node isn't a node it self.
** So my questions: How do I print a Mtree? (more specifically this https://github.com/tburette/mtree) and how do I print a tree recursively without a topnode? **
CodePudding user response:
def tree_as_tuple(root):
if(root.subtree == None): return root.obj
return (root.obj, tuple(map(tree_as_tuple, root.subtree.entries)))
and print one part of the tree at a time with
print(tree_as_tuple(next(iter(p_tree.root.entries))))
returns the following, which is acceptable
(24, ((24, ((80, ((89, )), (80, (71,80)))),)), (24, ((16, ((16, ((16,19)),)), (24, ((24, (24,)), 31, (23, 31)))))),)))
Thanks to @Stef for the feedback