2

So I'm working on an assignment for a data structures class, and one question is to create a put(key, value) method for an AVLTree. I know I have to adding the balancing method, but right now I'm just on the actual insertion. I want the function to work where you can create a tree and type newTree.put(key value) and have it work. Right now I have

class node:
        def __init__(self, key, value):
            self.key = key
            self.value = value
            self.left = None
            self.right = None
            self.height = 0        

class AVLTreeMap:
    def __init__(self, key, value):
        self.root = node(key, value)

    #inserting new key-value pair, NEED TO ADD BALANCING ABILITY      
    def put(self, key, value, height=0):
        if(key < self.root.key):
            if(self.root.left == None):
                self.root.left = node(key, value)
                self.root.left.height = height+1
            else:
                self.root = self.root.left
                self.put(key, value, height+1)
        else:
            if(self.root.right == None):
                self.root.right = node(key, value)
                self.root.right.height = height+1
            else:
                self.root = self.root.right
                self.put(key, value, height+1)

However, the recursive aspect of put just discounts the root, and creates a new tree of just one parent and that node as one child. Is this the right way to go about this, or is there an easier way? Also, if I do it this way, how do you recurse left and right in this method?

  • You are setting a new value for self.root, overwriting your actual root. Instead, make a recursive function call. Instead of self.root, you need something you can pass into the function (which can default to self.root for the first call) – Kenny Ostrom Mar 16 '19 at 17:08

0 Answers0