简体   繁体   中英

Desearilize binary search tree

I'm practicing for upcoming interviews and I'm trying to deserialise a binary search tree. I got it to work for serialising but I'm getting an argument number error but I don't see why.

I expect "5 2 1 # # # 35 18 7 # # 30 # # #" to be turned back into a tree.

Error:TypeError: _deserialize() takes exactly 2 arguments (3 given)

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM