我正在尝试为旅行营业员问题实施一棵树。我的特定树有5个目的地,彼此完全连接。
其中一个目的地保证始终是起始目的地,并且您只能访问每个目的地一次,但您必须返回的起始目的地除外(即如果您有[1,2,3] ,4,5] 1起始目的地,可能的移动顺序为1-3-5-2-4-1)
我尝试使用以下代码在python中实现一个树(因为我知道最大深度将是5,所以我强行使用它。)
class Node(object):
def __init__(self,value, city, children = [None, None, None, None]):
self.value = value
self.city = city
self.children = children
class Tree(object):
def __init__(self):
self.root = None
def insert(self,value,city):
newNode = Node(value,city)
if self.root is None:
self.root = newNode
else:
self._insert(1, newNode)
def _insert(self,depth, newNode):
if depth is 1:
for x in range(0,4):
if self.root.children[x] is None:
self.root.children[x] = newNode
return
elif self.root.children[3] is not None:
self._insert(2, newNode)
return
if depth is 2:
for x in range(0,4):
for y in range(0,3):
if self.root.children[x].children[y] is None:
self.root.children[x].children[y] = newNode
return
elif self.root.children[3].children[2] is not None:
self._insert(3, newNode)
return
if depth is 3:
for w in range(0,4):
for x in range(0,3):
for y in range(0,2):
if self.root.children[w].children[x].children[y] is None:
self.root.children[w].children[x].children[y] = newNode
return
elif self.root.children[3].children[2].children[1] is not None:
self._insert(4,newNode)
return
if depth is 4:
for w in range(0,4):
for x in range(0,3):
for y in range(0,2):
for z in range(0,1):
if self.root.children[w].children[x].children[y].children[z] is None:
self.root.children[w].children[x].children[y].children[z] = newNode
return
elif self.root.children[3].children[2].children[1].children[0] is not None:
self._insert(5,newNode)
return
if depth is 5:
for w in range(0,4):
for x in range(0,3):
for y in range(0,2):
for z in range(0,1):
for u in range(0,1):
if self.root.children[w].children[x].children[y].children[z].children[u] is None:
self.root.children[w].children[x].children[y].children[z].children[u] = newNode
return
elif self.root.children[3].children[2].children[1].children[0].children[0] is not None and w is 3 and x is 2 and y is 1 and z is 0 and u is 0:
print "The table is full"
def delete(self):
self.root = None
x = Tree()
x.insert(0, "Pretoria")
x.insert(60, "Johannesburg")
x.insert(1200, "Cape Town")
x.insert (600, "Durban")
x.insert(400, "Bloemfontein")
x.insert(1400, "Port Elizabeth")
我的root和第一级正确填充,但第二,第三,第四和第五级的所有子节点都填充与第一级完全相同。当我检查他们的记忆时,他们都填充了完全相同的内存空间,我不知道为什么。当以下代码行运行时会发生这种情况:
x.insert(1400, "Port Elizabeth")
尽管只有5个条目,但由于某种原因树已完全填充。
我最初尝试使用指针,但同样的问题就出现了。
长话短说,当你增加深度时,如何随着n的减少插入n-ary树?
此特定树具有以下属性: