0

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?

marco trevi
  • 219
  • 4
  • 12
  • 1
    "a string that represents the tree structure" *according to what logic*? Is this some particular sort of *traversal* of the tree? If so, in what order should the tree be traversed? Anyway, one obvious problem here is that writing `string + ...` *does not change* the variable `string`. It *creates a new value*, and then *ignores* that value. – Karl Knechtel Mar 03 '22 at 10:14
  • 1
    (Also: "Special cases aren't special enough to break the rules." If there are zero children, then you can handle that with the same logic - iterating zero times correctly does nothing. So there shouldn't be a need to separate out the base case logic here.) – Karl Knechtel Mar 03 '22 at 10:15
  • Sorry, I corrected the question – marco trevi Mar 03 '22 at 10:15
  • It is a depth first traversal. – marco trevi Mar 03 '22 at 10:16
  • Okay, and after that correction, what result do you get? If it is still wrong, *how* is it wrong? – Karl Knechtel Mar 03 '22 at 10:16
  • I get that nodes get printed multiple times and I don't understand why. – marco trevi Mar 03 '22 at 10:19
  • 3
    Please provide code that creates a small tree and then calls your function, reproducing the problem. – trincot Mar 03 '22 at 10:44

0 Answers0