Search code examples
pythonbinary-search-tree

Why do I get error when I set root to None initially for BST


Im getting TypeError: '<' not supported between instances of 'BST' and 'int' when I initially set root to None(see in code)

class BST:
    def __init__(self,key):
        self.key = key
        self.lchild = None
        self.rchild = None

    def insert(self,data):
        if self.key is None:
            self.key = BST(data)
            return
        if self.key < data:
            if self.lchild:
                self.lchild.insert(data)
            else:
                self.lchild = BST(data)
        else:
            if self.rchild:
                self.rchild.insert(data)
            else:
                self.rchild = BST(data)
    
    def preorder(self):
        print(self.key)
        if self.lchild:
            self.lchild.preorder()
        if self.rchild:
            self.rchild.preorder()



root = BST(None)

list1 = [20,34,1,3,4,78]
for i in list1:
    root.insert(i)

root.preorder()

When I set root to an int it works fine


Solution

  • The comments say you should debug. They aren't wrong, but maybe it's hard to see how to do that when you don't understand the error.

    The error means generally that you are comparing a BST to an int somewhere and that this is not defined.

    Let's have a look at the types by adding

    print(f"{type(self.key)=},\t{type(data)=}")
    

    to the beginning of your insert function.

    We get:

    type(self.key)=<class 'NoneType'>,  type(data)=<class 'int'>
    type(self.key)=<class '__main__.BST'>,  type(data)=<class 'int'>
    Traceback (most recent call last):
      File "tmp.py", line 36, in <module>
        root.insert(i)
      File "tmp.py", line 12, in insert
        if self.key < data:
    TypeError: '<' not supported between instances of 'BST' and 'int'
    
    

    So apparently we first execute the function correctly once with the key being None and then again with the key being a BST object. The data is always an int.

    But you have not defined how an int and a BST can be compared.

    Do you want to do that? Probably not. Because your key is supposed to be an int, right? You have a BST but the key inside the BST should be an int. So you don't need the BST(data) when you assign the key in the case where it is none. instead:

    if self.key is None:
        self.key = data
        return