gpt4 book ai didi

python - 反序列化二叉搜索树

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:04 26 4
gpt4 key购买 nike

我正在为即将到来的面试练习,我正在尝试反序列化二叉搜索树。我让它用于序列化,但我收到参数编号错误,但我不明白为什么。

我希望“5 2 1 # # # 35 18 7 # # 30 # # #”变回一棵树。

错误:TypeError:_deserialize() 正好接受 2 个参数(给定 3 个)

    def __init__(self,value = None):
self.value = value
self.left_child = None
self.right_child = None


class BinarySearchTree:
def __init__(self):
self.root = None


def insert(self,value):
if self.root is None:
self.root = Node(value)
else:
self._insert(value, self.root)

def _insert(self, value, current_node):
if value < current_node.value:
if current_node.left_child is None:
current_node.left_child = Node(value)
else:
self._insert(value,current_node.left_child)

elif value > current_node.value:
if current_node.right_child is None:
current_node.right_child = Node(value)
else:
self._insert(value,current_node.right_child)
else:
print("Value already inserted!")


def serialize(self,serial):
if self.root is not None:
return ' '.join(self._serialize(self.root, serial))


def _serialize(self, current_node, serial): #Post order
if current_node is not None:
serial.append(str(current_node.value))
self._serialize(current_node.left_child, serial)
self._serialize(current_node.right_child, serial)
else:
serial.append("#")

return serial


def deserialize(self, serial):
vals = iter(serial.split())
return self._deserialize(self, vals)

def _deserialize(self, vals):
value = next(vals)
if value == "#":
return None

node = Node(int(value))
node.left_child = self._deserialize(vals)
node.right_child = self._deserialize(vals)
return node




tree = BinarySearchTree()
tree.insert(5)
tree.insert(2)
tree.insert(1)
tree.insert(35)
tree.insert(18)
tree.insert(7)
tree.insert(30)
root = Node(3)
serial = []
serial = tree.serialize(serial)
print(serial)


tree.deserialize(serial)

最佳答案

正如@Primusa 指出的那样,return self._deserialize(self, vals) 应该是return self._deserialize(vals)

关于python - 反序列化二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55779367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com