Create and Inorder Method in BST in DSA Python
by DataFlair Team
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
Tags: binary search tree in dsa pythoncreate and inorder method in binary search tree in dsa pythoncreate and inorder method in bst in dsa pythondsa pythondsa python practicaldsa python programdsa python program on creation and inorder method in bstdsa using python
DataFlair Team
DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.