Search code examples
pythonbinary-search-tree

Creating a Binary Search Tree using Binary Search Tree class Implementation


I have defined the BinarySearchTree class below:

class BinarySearchTree:

    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def insert(self, new_data):
        if new_data == self.data:
            return
        elif new_data < self.data:
            if self.left == None:
                self.left = BinarySearchTree(new_data)
            else:
                self.left.insert(new_data)
        else:
            if self.right == None:
                self.right = BinarySearchTree(new_data)
            else:
                self.right.insert(new_data)

    def search(self, find_data):
        if self.data == find_data:
            return True
        elif find_data < self.data and self.left != None:
            return self.left.search(find_data)
        elif find_data > self.data and self.right != None:
            return self.right.search(find_data)
        else:
            return False

    def get_data(self):
        return self.data

    def set_data(self, new_data):
        self.data = new_data

    def get_left(self):
        return self.left

    def get_right(self):
        return self.right

Using this class implementation now I need to create a binary tree as shown in the vertical representation: enter image description here

>>> bst = create_bst()
    print_tree(bst, 0)
27
(L)    14
(L)        10
(R)        19
(R)    35
(L)        31
(R)        42

With my code here:

def create_bst():
    root = BinarySearchTree(27)
    root.insert(14)
    root.insert(10)

    root.get_left().insert(19)
    root.get_left().insert(35)
    root.get_left().get_left().insert(31)
    root.get_left().get_right().insert(42)
    return root

This is the representation I'm getting:

27
(L)    14
(L)        10
(R)            31
(R)        19
(R)            35
(R)                42

Solution

  • It seems to be working fine so far. Just put all the elements directly into root without using get_left, get_right (since you are inserting them into the wrong node).

    def create_bst():
        root = BinarySearchTree(27)
        root.insert(14)
        root.insert(10)
    
        root.insert(19)
        root.insert(35)
        root.insert(31)
        root.insert(42)
        return root