【发布时间】:2022-01-27 04:20:57
【问题描述】:
我正在尝试根据这篇文章实现一个 n-arry 树: [这里][1] 并且在尝试定义添加子项的函数时出现错误:
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __str__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__str__(level+1)
return ret
# trying to implement this method si that I can get rid of
# calling root.children[0].children
def add_child(self, obj):
self.children.append(obj)
def __repr__(self):
return '<tree node representation>'
root = node('grandmother')
root.children = [node('daughter'), node('son')]
root.children[0].children = [node('granddaughter'), node('grandson')]
root.children[1].children = [node('granddaughter'), node('grandson')]
root.add_child([node((1)), node(2)]) # error
print (root)
我希望能够创建一棵树并打印它。 [1]:Printing a Tree data structure in Python
【问题讨论】:
-
不过,这个错误实际上说明了什么?
-
您正在尝试将节点的 列表 添加为单个子节点。您要么需要一个
add_children方法,该方法使用self.children.extend一次添加多个孩子,要么多次调用add_child,每个孩子添加一个。