我试图在Python中实现2-3树(夏天的乐趣)。
我处于一个阶段,如果某个节点的子节点少于2个,我想在其“#kids;"”中插入一个新节点。列表。
我认为这是将新节点对象附加到子列表的简单过程。但是,这似乎是从" []"设置新节点的子列表。建设到" [指针]"。那指针指向......新对象本身!并继续递归,直到堆栈溢出。所有这些都是通过简单的追加来触发的!
有什么想法?我可以编写一个解决方法,但我真的想了解这背后的工程。
class Node:
def __init__(self, data = [], kids = []):
if not isinstance(data, list):
data = [data]
self.data = data
self.kids = kids
class TwoThreeTree:
def __init__(self):
self.root = None
def insert(self, n):
if not isinstance(n, Node):
n = Node(n)
if not self.root:
self.root = n
else:
self.root = self._insert(n, self.root)
def _insert(self, n, cur):
if len(cur.kids) <= 2:
cur.kids.append(n) #Issue occurs here
elif n.data <= cur.data[0]:
cur.kids[0] = self._insert(n, cur.kids[0])
elif n.data <= cur.data[1]:
cur.kids[1] = self._insert(n, cur.kids[1])
elif len(cur.kids) == 3:
cur.kids[2] = self._insert(n, cur.kids[2])
cur = self.reorg(cur)
return cur
额外:测试的完整代码
def reorg(self, cur):
cur.kids = sorted(cur.kids, key=lambda x: x.data)
if len(self.root.kids) == 1:
other = cur.kids[0]
cur.kids = []
if cur.data == min(cur.data, other.data):
small = cur
big = other
else:
small = other
big = cur
cur.data = [small.data[-1], big.data[-1]]
cur.kids =[small, big]
elif len(cur.kids) == 4:
kid1 = Node([cur.kids[0].data[-1], cur.kids[1].data[-1]],
[cur.kids[0], cur.kids[1]])
kid2 = Node([cur.kids[2].data[-1], cur.kids[3].data[-1]],
[cur.kids[2], cur.kids[3]])
cur.kids = [kid1, kid2]
cur.data = [cur.kids[0].data[-1], cur.kids[1].data[-1]]
return cur
def preOrder(self, cur=-1):
if cur == -1:
cur = self.root
if cur:
print(cur.data)
if cur.kids:
for kid in cur.kids:
self.preOrder(kid)
t = TwoThreeTree()
for x in [1, 2, 3, 4, 5]:
t.insert(x)
t.preOrder()