简体   繁体   English

如何访问n叉树中节点的父节点?

[英]How to access parent of a node in n-ary tree?

I am trying to create a Node class that implements an n-ary tree but I also want to keep track of the parent of each node to trace back to the root.我正在尝试创建一个实现 n 叉树的节点 class 但我也想跟踪每个节点的父节点以追溯到根。

class Node(object):
    def __init__(self, state, children=None, parent=None):
        self.state = state
        self.children = children or []
        self.parent = parent
    def add(self, obj):
        self.children.append(Node(obj))
        Node(obj).parent = self.state

This is what I have been working on.这就是我一直在做的事情。 But when I check to see a node's parent, it prints None.但是当我查看节点的父节点时,它会打印无。 In a binary tree, checking if the child was to the left or right makes it easy but for an n-ary tree, I don't really understand how to go about it with explicitly making it the parent.在二叉树中,检查孩子是在左边还是右边很容易,但是对于 n 叉树,我真的不明白如何通过明确地将其设为父级来了解它。

I am pretty new to Python and coding so I would really appreciate it if anyone could help out!我对 Python 和编码很陌生,所以如果有人能提供帮助,我将不胜感激! Thank you!谢谢!

EDIT:编辑:

I ran this on the IDE:我在 IDE 上运行了这个:

>>> n = Node(4)
>>> l = [1,2,3]
>>> for i in l:
    n.add_child(i)


>>> n.children.state
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    n.children.state
AttributeError: 'list' object has no attribute 'state'
>>> for child in n.children:
    print(child.state)


1
2
3
>>> for child in n.children:
    print(child.parent)


None
None
None
>>> 

instead of self.parent = parent而不是self.parent = parent

you want to do你想做

self.parent = None # for root node only

for child in children:
  child.parent = self
self.children.append(Node(obj))

Here you are creating a Node instance on the fly and appending it to the children list在这里,您正在动态创建一个 Node 实例并将其附加到子列表中

Node(obj).parent = self.state

That is an extra instance of Node on the fly which you are assigning its parent to be self.state这是一个额外的 Node 实例,您将其父级分配为 self.state

I think you are trying to do something like this:我认为你正在尝试做这样的事情:

node = Node(obj)
node.parent = self
self.children.append(node)

With this you are creating an instance of Node and storing its reference in the variable node, then assigning its parent to be the current Node instance (with the self reference) and saving the reference to its children list.这样,您将创建一个 Node 实例并将其引用存储在变量 node 中,然后将其父级分配为当前 Node 实例(带有自引用)并将引用保存到其子级列表。

Also, you could do:另外,你可以这样做:

self.children.append(Node(obj, None, self))

since you are assigning the parent in the constructor.因为您在构造函数中分配父级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM