Skip to main content
5 of 8
added 317 characters in body

Binary Search Tree implementation in Python 3

Please review my BST Code

1. Class node

class Node:

2. Constructor

class Node:
'''this is the constructor'''
def __init__(self, data):
    self.left = None
    self.right = None
    self.data = data

3. Insert node

def insert(self, data):
    ''' this function work is insert the data in bst'''
    if self.data:
        '''insert left side value '''
        if data < self.data:
            if not self.left:
                self.left = Node(data)
            else:
                self.left.insert(data)
            '''insert right side value'''
        elif data > self.data :
            if not self.right :
                self.right = Node(data)
            else:
                self.right.insert(data)
    else:
        self.data = data

4. Node in delete any value

def getMinValue(self,node):
     '''this fuction work is get minimum value'''
    current = node
    while current.left is not None:
        current = current.left
    return current
def delValue(self,data):       
    '''this fuction work delete value'''
    if data < self.data:
        self.left = self.left.delValue(data)
    elif data > self.data:
        self.right = self.right.delValue(data)
    else:
        if self.left is None:
            temp = self.right
            self = None
            return temp
        elif self.right is None:
            temp = self.left
            self = None
            return temp
        temp = self.getMinValue(self.right)
        self.data = temp.data
        self.right = self.right.delValue(temp.data)
    return self

5. Node in search any value

'''this function work finde a value in bst or return True or False'''
    if data == self.data:
        return print(True)
    if data < self.data:
        if self.left:
            self.left.getSearchValue(data)
    if data > self.data:
        if self.right:
            self.right.getSearchValue(data)
        return print(False)

6. Print tree

'''this function work print a tree'''
    if self.left:
        self.left.printTree()
    print(self.data)
    if self.right:
        self.right.printTree()