简体   繁体   中英

Python Binary Search Tree with key and value

I need to implement a Binary Search Tree class as homework but I struggle making the insert function. I have looked through Google a lot to find some solutions or possibilities on how to do it but none of them has used a key and value (mostly just value) or if they used a key aswell, they had tons of seperate functions which I am not allowed to do I think.

So the pre-built is simply that:

class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.left = self.right = None

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

    def __len__(self):
        return self.size

    def insert(self, key, value):
        pass

    def remove(self, key):
        pass

    def find(self, key):
        pass

Now the thing is, if I want to check for example whether the value is smaller or bigger than a current Node to put it either right or left, I get Errors such as "root is not defined" or "root.right" has no such attribute etc... And I guess that makes sense because self.root is declared as None.

But how do I actually fix it now to make the insert function work?

I am a little confused by this task as it uses key + value, so I need to insert the value bound to the specific key and in case the key already existed, overwrite its value.

You didn't specify, but I'm guessing the point of the keys is to determine if a particular key is already in the tree, and if so, replace the related node's value in O(1) runtime complexity.

So when you're inserting a node, you will first check the dictionary for the key (you will initialize an empty dictionary yourself in __init__ ). If it already is there, then you simply just need to replace the value of the node for that particular key. Otherwise, you add the new node the same way that you would in any BST, and also remember to update your dictionary to map the key to it's node.

its 5 in the morning so this might be all wrong, but here goes:
the key is what we are sorting by, the values aren't interesting
your insert function should probably look something like this:

def insert(self, key, value):
        if self.root = None:
            self.root = Node(key,value)
            return
        #regular binary tree traversal (comparing the key) to find where to insert, lets assume we need to insert on the left
        parent.left = Node(key,value)

can you figure it out from here or would you like more direction

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