1

I have created a search function which is supposed to find a value in a binary tree and return True if the value is found and False if it isn't.

The tree is correct, I've tested.

The different cases work when I print a string "Found" or "Not found". But return True doesn't work.

Here's the code of my Tree class :

class Tree(object):

    def __init__(self):
        self.fg = None
        self.fd = None
        self.data = None

    def insert(self, data):
        if self.data == None:
            self.data = data

        elif self.data > data:
            if self.fg == None:
                self.fg = Tree()
            self.fg.insert(data)

        elif self.data < data:
            if self.fd == None:
                self.fd = Tree()
            self.fd.insert(data)

    def search(self, data):
        if self.data == None:
            return False
        elif self.data == data:
            print("Found")
            return True

        if self.data > data:
            if self.fg == None:
                return False
            else:
                self.fg.search(data)

        elif self.data < data:
            if self.fd == None:
                return False
            else:
                self.fd.search(data)

tree = Tree()

tree.insert(6)
tree.insert(3)
tree.insert(4)
tree.insert(5)

print(tree.search(6), "\n")
print(tree.search(7), "\n")
print(tree.search(3), "\n")
print(tree.search(4), "\n")
print(tree.search(5), "\n")

Here's the result :

Found
True 

Not found
False 

Found
None 

Found
None 

Found
None

Thank you for your help.

Killkenny
  • 11
  • 2

1 Answers1

2

You should return the value of your recursive calls

return self.fg.search(data)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218