Skip to main content
7 of 8
edited tags

Binary Search Tree implementation in Python 3

Please review my BST Code

1. Class node

class Node:

2. Constructor

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

3. Insert node

def insert(self, data):
    if self.data:
        if data < self.data:
            if not self.left:
                self.left = Node(data)
            else:
                self.left.insert(data)
        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):
    current = node
    while(current.left is not None):
        current = current.left
    return current
def delValue(self,data):       
    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

def getSearchValue(self,data):
    if data == self.data:
        return print(self.data,"True")
    if data < self.data:
        if self.left:
            self.left.getSearchValue(data)   
    if data > self.data:
        if self.right:
            self.right.getSearchValue(data)

6. Print tree

def print_tree(self):
    if self.left:
        self.left.print_tree()
    print(self.data)
    if self.right:
        self.right.print_tree()