Python Recusrive Method returns NoneType

Question:

So, (It’s about the search method), the method is recursive but when I try to return my self.key and self.value, the functions returns a NoneType, how can I fix this?

(There is more to the class, but this is the relevant part, the other parts of code have no effect on this part)

I’ve seen other solutions where you have to return the whole method (In my case that would be: return search(self, key) ) but those just give me an infinite loop

class BinairySearchTree:

def __init__(self, key=None, value=None, lefttree=None, righttree=None):
    self.key = key
    self.value = value
    self.lefttree = lefttree
    self.righttree = righttree

def insert(self, key, value):
    if self.key != None:
        if key > self.key:
            if self.righttree != None:
                self.righttree.insert(key, value)
            else:
                self.righttree = BinaireZoekBoom(key, value)
        elif key == self.key:
            self.key = key
            self.value = value
        elif key < self.key:
            if self.lefttree != None:
                self.lefttree.insert(key, value)
            else:
                self.lefttree = BinaireZoekBoom(key, value)
    elif self.key == None:
        self.key = key
        self.value = value

def search(self, key):
    if key > self.key:
        self.righttree.search(key)
    elif key == self.key:
        return self.key, self.value
    elif key < self.key:
        self.lefttree.search(key)
Asked By: Lander Geeraert

||

Answers:

I think I just saw the problem: your search function doesn’t propagate the found node up the tree. You have to return a value at every level to get the result back to the original caller.

def search(self, key):
    if key > self.key:
        return self.righttree.search(key)
    elif key == self.key:
        return self.key, self.value
    elif key < self.key:
        return self.lefttree.search(key)
Answered By: Prune
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.