Friday, October 25, 2024

BST python



class Tree:
  def __init__(self,data):
    self.data = data
    self.left = None
    self.right = None
 
  def is_empty(self):
    return self.data is None
 
  def insert(self,value):
    if value < self.data:
      if self.left is None :
        self.left = Tree(value)
      else:
        self.left.insert(value)
   
    if value > self.data :
      if self.right is None:
        self.right = Tree(value)
      else:
        self.right.insert(value)
       
  def show_left(self):
    current = self.left
    while current:
      if current.data != None:
        print(current.data)
      current = current.left
    print()
   
  def show_right(self):
    current = self.right
    while current:
      if current.data != None:
        print(current.data)
      current = current.right
    print()
   
def delete(root):
  value=-3
  if root:
    delete(root.left)
    delete(root.right)
    if root.data == value and root.data != None:
      root.data = None
     
     
def preorder(root):
  if root and root.data != None:
    print(root.data)
    preorder(root.left)
    preorder(root.right)

def postorder(root):
  if root and root.data != None:
    postorder(root.left)
    postorder(root.right)
    print(root.data)

def inorder(root):
  if root and root.data != None:
    inorder(root.left)
    print(root.data)
    inorder(root.right)
   
   
   
   
root = Tree(1)
root.insert(2)
root.insert(3)
root.insert(4)
root.insert(-1)
root.insert(-2)
root.insert(-3)
root.show_left()
root.show_right()
delete(root)
root.show_right()
root.show_left()
preorder(root)
postorder(root)
inorder(root)

No comments:

Post a Comment

virtual environment on python on Ubuntu

 # 1. Update system and install Python tools sudo apt update && sudo apt install python3-pip python3-venv -y # 2. Setup Django in a ...