来自http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html
让我们创建一个python类来表示一棵树。我们需要一些方法 将数据存储在节点中,并以某种方式指示任何子节点,或 子树。
class node(object): def __init__(self, value, children = []): self.value = value self.children = children
哇!这似乎太容易了......不管你信不信,它确实如此 工作。让我们使用我们的新课来存储我们的家谱...
tree = node("grandmother", [ node("daughter", [ node("granddaughter"), node("grandson")]), node("son", [ node("granddaughter"), node("grandson")]) ]);
我希望能够同时获取每个node
实例的子项和父项,所以我认为我需要定义其父项及其子项
class node(object):
def __init__(self, value, children = [], parent = []):
self.value = value
self.children = children
self.parent = parent
但问题是每个节点的子节点和父节点都会有一个副本。如果我更改其值,我将不得不更改其副本中的所有值。在C ++中,没有这样的问题,因为我们可以通过将指针存储到其子节点以及仅存在于其中的父节点来引用节点的子节点和父节点。我想知道如何在Python中实现这样的树?感谢。
答案 0 :(得分:5)
您可以在节点构造函数中指定子项的父项:
class node(object):
def __init__(self, value, children = None):
self.value = value
self.children = children or []
self.parent = None
for child in self.children:
child.parent = self
答案 1 :(得分:1)
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
tree = [node("grandmother", [ node("daughter", [ node("granddaughter"), node("grandson")]), node("son", [ node("granddaughter"), node("grandson")]) ])];
def familyValues(targetName, siblings = []):
family = []
for sibling in siblings:
if sibling.value == targetName:
family.append(sibling)
family = family + sibling.children
break
else:
children = familyValues(targetName, sibling.children)
if len(children) > 0:
children.append(sibling)
family = children
return family
myFamily = familyValues('daughter', tree)
for sibling in myFamily:
print(sibling.value)
除非你明确克隆它们,否则没有python中的对象副本