使用“parent”supp在Python中构建树

2024-06-17 10:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:根的子对象本身就是子对象。我在Python中构建数据结构是新的,所以我编写代码就像我写C++一样。这是我的密码:

class node:
    key = None
    value = None
    parent = None
    children = []

    def __init__(self,key,val):
        self.key = key
        self.val = val

if __name__ == "__main__":
    root = node(50,50)
    child = node(20,20)
    child.parent = root
    root.children.append(child)
    print(root)
    print(child)
    print(root.children)
    print(child.parent)
    print("Why does child have itself as a child??!!")
    print(child.children)

我似乎不知道问题出在哪里


Tags: 对象key代码selfnonenodechild密码
1条回答
网友
1楼 · 发布于 2024-06-17 10:15:54

您使用的是类属性,而您应该使用实例属性

class Node:
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.children = []
        self.parent = None

root = node(50, 50)
child = node(20, 20)
child.parent = root
root.children.append(child)

您可以修改__init__以简化树的构建

class Node:
    def __init__(self, key, val, parent=None):
        self.key = key
        self.val = val
        self.parent = parent
        if parent is not None:
            parent.children.append(self)

root = node(50, 50)  # sets root.parent = None
child = node(20, 20, root)  # sets child.parent = root and adds child to root.children

相关问题 更多 >