0

I am writing a code to search for elements in a binary search tree. I wrote the code inside the class BinarySearchTree but it returns None.

class Node:
    def __init__(self, info):
        self.info = info  
        self.left = None  
        self.right = None 
        self.level = None

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

    def search(self, key):
        a = search(self.root)
        if self.root is None or self.root == key:
            return self.root
        if key > self.root:
            return self.search(self.root.right)
        return self.search(self.root.left)

I tried storing self.search(self.root.right) and self.search(self.root.left) into variables and then returned them using or but still I get None as output.

class Node:
    def __init__(self, info):
        self.info = info  
        self.left = None  
        self.right = None 
        self.level = None

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

    def search(self, key):
        a = search(self.root)
        if self.root is None or self.root == key:
            return self.root
        if key > self.root:
            a = self.search(self.root.right)
        b = self.search(self.root.left)
        return a or b

I do not understand what I am doing wrong here and why the output is coming as None.

(I am a beginner and this is my first time asking a question here so please forgive me if I have made any silly mistake.)

This was my input

r = Node(1)
r.left = Node(2)
r.right = Node(3)
r.left.left = Node(4)
r.left.right = Node(5)
r.right.right = Node(6)
r.right.left = Node(7)
AD_101
  • 1
  • 1
    There's a bit of confusion in your use of node references and key/info values. Your search() method seems to expect a key but compares it of object references in root/left/right properties (which will never be True). Then you use nodes as the search parameter when you recurse deeper. Also, you should show how you create the BinarySearchTree instance and what you put in its root property (If that remains None, then your search will never return anything). Finally, `a = search(...` should fail immediately – Alain T. Mar 11 '21 at 20:40
  • `b = BinarySearchTree() b.search(r, 4)` This is the way I accessed the function in the first code – AD_101 Mar 12 '21 at 04:21
  • Expanding on what @Alain wrote, your implementation is missing most of what's necessary, and your binary tree example is also not even a binary search tree, so BST algorithms wouldn't work on it anyway. Please look at [How to implement a binary tree?](https://stackoverflow.com/questions/2598437/how-to-implement-a-binary-tree) – Welbog Mar 12 '21 at 11:36

0 Answers0