反序列化二叉搜索树

问题描述 投票:1回答:1

我正在练习即将进行的采访,我正在尝试反序列化二叉搜索树。我得到了序列化的工作,但我得到一个参数号错误,但我不明白为什么。

我希望将“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)

python algorithm binary-search-tree
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.