【发布时间】:2016-10-22 12:55:22
【问题描述】:
我正在尝试定义一个易于管理的树类(添加节点、获取子节点并以 dfs 或 bfs 样式遍历它),但我对 python 了解一点,运行时遇到错误我的代码:
AttributeError: 'Tree' 对象没有属性 'get'
这是我的代码,现在我刚刚实现了节点的添加:
class Tree(dict):
def __init__(self):
self = {}
def add(self, node, child):
if self.get(int(node)):
childs = self.get(int(node))
childs.append(int(child))
self.update({int(node):childs})
else:
self.update({int(int(node)):[int(child)]})
def main():
tot = int(input("Cantidad de relaciones: "))
t = Tree()
for i in range (0, tot):
for i in range (0,1):
a = []
a.extend(input().split())
t.add(a[0], a[1])
print(t)
main()
【问题讨论】:
标签: python list dictionary tree