I am trying to repr开发者_Python百科esent a hierarchy using namedtuple
. Essentially, every node has three attributes relevant to the hierarchy: parent
, leftChild
and rightChild
(they also have some attributes that carry the actual information, but that is not important for the question). The problem is the circular reference between parents and children. Since I need to specify all values at construction time, I run into problems because parents need the children to be constructed first, and children need the parents to be constructed first. Is there any way around this (other than using a custom class instead of tuples)?
No, there is not.
Remove parent field. You can still implement any tree-manipulation operations efficient without keeping reference to parent node.
One trick is not to use an object reference, but instead, a symbolic ID that you maintain in a hash table.
精彩评论