在python中从树递归生成字符串
我正在使用networkx库,我需要将树T
转换为表示树结构的字符串。我正在尝试递归地执行此操作,但我无法正确执行。 树的节点具有诸如“children”(该节点的邻居数量)和“nodeID”(该节点的唯一整数标识符)之类的属性。 这是我的代码:
...
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)
对于诸如 1-->2、1-->3、2-->4、2-->5、2-->6 之类的树,所需的输出是以下:124563
我错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论