Site icon DataFlair

Create and Inorder Method in BST in DSA Python

Program 1

# Implementation of Binary Search Tree
import os
class Node:
    def __init__(self):
        self.ladd=None
        self.data=None
        self.radd=None

class Tree:
    def __init__(self):
        self.root=None
        #Create Method
    def createTree(self,r,new1):
        if(new1.data<r.data):
            if(r.ladd==None):
                r.ladd=new1
            else:
                self.createTree(r.ladd,new1)  # Recursion
        if(new1.data>r.data):
            if(r.radd==None):
                r.radd=new1
            else:
                self.createTree(r.radd,new1)  # Recursion    

        if(new1.data==r.data):
            print("duplicate element not allowed .")        

     #Inorder Method           
    def inorder(self,p):
        if(p!=None):
            self.inorder(p.ladd)   # left
            print(p.data,end="  ")  # Node
            self.inorder(p.radd)  #right


#Main Menu
T=Tree()
os.system('cls')
while(1):
    print("\n-----------------Tree Menu------------------")
    print("                 1.Create Tree ")
    print("                 2.Inorder ")
    print("                 3.Preorder ")
    print("                 4.Postorder ")
    print("                 5.Exit ")
    print("----------------------------------------------")
    choice=int(input("Enter your choice"))
    
    if(choice==1):
       ch="y"
       while(ch=="Y" or ch=="y"):
           n=int(input("Enter an element"))
           new1=Node()
           new1.ladd=None
           new1.data=n
           new1.radd=None
           if(T.root==None):
              T.root=new1
           else:
              T.createTree(T.root,new1)
           ch=input("Want to continue: ")
    elif(choice==2):
        print("Inorder Elements: ")
        T.inorder(T.root)     
    else:
        break

 

Exit mobile version