在python中从树递归生成字符串

发布于 2025-01-11 09:02:38 字数 781 浏览 0 评论 0原文

我正在使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文