I am using the networkx library, and I need to convert a tree T
into a string that represents the tree structure. I am trying to do it recursively, but I cannot get it right.
Nodes of the tree have attributes like "children"
, which is the number of neighbors of that node, and "nodeID"
which is a unique integer identifier of that node.
Here's my code:
...
import networkx as nx
...
def treeToString(tree, node, string):
children = tree.nodes[node]["children"]
if children == 0:
# we are on a leaf node
string = string + str(tree.nodes[node]["nodeID"])
return string
else:
string = string + str(tree.nodes[node]["nodeID"])
for child in nx.neighbors(tree, node):
string = string + str(treeToString(tree, child, string))
return string
stringifiedTree = treeToString(T, root, "")
print(stringifiedTree)
The desired output would be, for a tree such as 1-->2, 1-->3, 2-->4, 2-->5, 2-->6 the following: 124563
What am I getting wrong?